Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 435
John B Avatar asked Apr 09 '09 20:04

John B


People also ask

How to get the selected value of RadioButtonList in JavaScript?

You can assgin the onclick event for the RadioButtonList, when you click one rediobutton, it will fire the GetRadioButtonValue fuction. It will find the checked rediobutton, and move its value into textbox.

How to check if RadioButtonList is checked in c#?

getElementById("<%=RadioButtonList1. ClientID%>"); var flag=false; for (var i = 0; i < rbl1. length; i++) { if (radio[i]. checked) flag=true; } if(flag==true) alert('radiobuttonlist1 is selected');

How to check if Radio button is checked asp net?

Checking if any of them are checked could be done like this: var radioButtonCheckedInGr1 = GetRadioButtons(Form, "Gr1"). Any(i => i. Checked);


2 Answers

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.

like image 139
Andrew Hare Avatar answered Oct 16 '22 19:10

Andrew Hare


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
}
like image 23
Martin Clarke Avatar answered Oct 16 '22 18:10

Martin Clarke