2017-10-12 99 views
-1

我想找到一种方法来在用户没有在下拉列表中选择一个值时抛出一个错误。我尝试了很多解决方案,这里提供了。但是,没有人可以work.This是我的代码NullException在RadioButtonList中没有选择任何值时的错误

protected void Button1_Click(object sender, EventArgs e) 
    { 
     if (RadioButtonList1.SelectedItem.Value == null) 
      { 
       //Throw error to select some value before button click 
      } 

     if (RadioButtonList1.SelectedItem.Value == 'male') 
      { 
       //Step1 
      } 
     if (RadioButtonList1.SelectedItem.Value == 'female') 
      { 
       //Step2 
      } 
    } 

试图与

if (RadioButtonList1.SelectedIndex == -1) 

更换,但同样没有工作。有任何想法吗?从评论

+1

如果没有选择,什么*是* SelectedIndex,如果不是'-1'?当你调试时,实际价值是多少? – David

+1

“RadioButtonList1.SelectedItem.Value == null”的作品? SelectedItem应该为空。 –

+0

执行代码仅在选择单选按钮时执行,当用户单击时没有选择时出现错误 - 对象引用未设置为对象的实例...并且没有“RadioButtonList1.SelectedItem.Value”== null不工作 – rakesh

回答

0

这将是更容易为你如果选择的项目被放入变量调试:

var selectedItem = RadioButtonList1.SelectedItem; 
if (selectedItem == null) 
{ 
    throw new Exception("Please select"); 
} 
else if (selectedItem.Value == "male") 
{ 
    // step 1 
} 

单选按钮是具体的。如果没有选择任何内容,则不存在selectedItem,因此不存在不存在的对象的值。

编辑:将调试点放在第一行,var selectedItem = ..所以你将在悬停知道它有什么确切的价值。

编辑2:总是检查你的对象是否不为空。您在评论中的错误是由于您在实际对象不存在时立即尝试访问对象属性所致。

1

报价:

(勒凯什)仅当选择了单选按钮的实际工作的代码执行时,当用户点击没有选择我的错误 - 不设置为一个对象的实例对象引用...和NO “RadioButtonList1.SelectedItem.Value” == NULL不起作用

那是你的方式!错误的原因是:RadioButtonList1.SelectedItem为空。所以没有的值。所以说:只要检查

if (RadioButtonList1.SelectedItem == null) {...} 

编辑澄清讨论:

if (RadioButtonList1.SelectedItem == null) 
{ 
    //Throw error to select some value before button click 
} 
else if (RadioButtonList1.SelectedItem.Value == "...") 
{ 
    .... 
} 
+0

我试过了。但它跳过'RadioButtonList1.SelectedItem == null'移动到具有相同错误的下一个条件 - 请参见图片:http://ibb.co/itapFb – rakesh

+1

它不会跳过!它执行。但它也会执行发生错误的行。尝试块中的“返回”或“else if”。 –

+0

谢谢!它执行了多重条件。我必须在一次执行后结束该块。再次感谢。 – rakesh

相关问题