Search code examples
c#asp.netvalidationradiobuttonlist

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


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))

Solution

  • 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
    }