views:

410

answers:

3

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  A: 

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.

Andrew Hare
A: 

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>
Keltex
+1  A: 

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
}
Martin Clarke
By the way, it should be "return list.SelectedItem != null".
SkippyFire
good point, I'll edit the error out.
Martin Clarke