What is the best way to see if a RadioButtonList has a selected value?

 ̄綄美尐妖づ 提交于 2020-01-01 02:26:30

问题


I am using:

if (RadioButtonList_VolunteerType.SelectedItem != null)

or how about:

if (RadioButtonList_VolunteerType.Index >= 0)

or how about (per Andrew Hare's answer):

if (RadioButtonList_VolunteerType.Index > -1)

To those who may read this question, the following is not a valid method. As Keltex pointed out, the selected value could be an empty string.

if (string.IsNullOrEmpty(RadioButtonList_VolunteerType.SelectedValue))

回答1:


In terms of readability they all lack something for me. This seems like a good candidate for an extension method.

public static class MyExtenstionMethods 
{   
  public static bool HasSelectedValue(this RadioButtonList list) 
  {
    return list.SelectedItem != null;
  }
}


...

if (RadioButtonList_VolunteerType.HasSelectedValue)
{
 // do stuff
}



回答2:


Those are all valid and perfectly legitimate ways of checking for a selected value. Personally I find

RadioButtonList_VolunteerType.SelectedIndex > -1

to be the clearest.




回答3:


I recommend:

RadioButtonList_VolunteerType.SelectedIndex>=0. 

According to the Microsoft Documentation:

The lowest ordinal index of the selected items in the list. The default is -1, which indicates that nothing is selected.

string.IsNullOrEmpty(RadioButtonList_VolunteerType.SelectedValue) will not always work as you can have a ListItem with an empty value:

<asp:ListItem Value=''>This item has no value</asp:ListItem>



回答4:


The question revolves more around whether to check for null or check value of an int. Martin's great extension method could also be written:

public static bool HasSelectedValue(this ListControl list)
{
    return list.SelectedIndex >= 0;
}

The MSDN documentation for a ListControl states:

Default for SelectedItem is null.

Default for SelectedIndex is -1.

So either are valid ways and both work. The question is which is the best way. I'm guessing SelectedIndex as it is a value type operation rather than reference type operation. But I don't have anything to back that up with.



来源:https://stackoverflow.com/questions/735775/what-is-the-best-way-to-see-if-a-radiobuttonlist-has-a-selected-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!