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))
Those are all valid and perfectly legitimate ways of checking for a selected value. Personally I find
to be the clearest.
I recommend:
According to the Microsoft Documentation:
string.IsNullOrEmpty(RadioButtonList_VolunteerType.SelectedValue) will not always work as you can have a ListItem with an empty value:
In terms of readability they all lack something for me. This seems like a good candidate for an extension method.
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:
The MSDN documentation for a ListControl states:
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.