How can I find the selected RadioButton's value in ASP.NET? How can I find the selected RadioButton's value in ASP.NET? asp.net asp.net

How can I find the selected RadioButton's value in ASP.NET?


You want to do this:

RadioButton selRB = radioButtonsContainer.Controls.OfType<RadioButton>().FirstOrDefault(rb => rb.Checked);if(selRB != null){    int registrationTypeAmount = Convert.ToInt32(selRB.ToolTip);    string cbText = selRB.Text;}

where radioButtonsContainer is the container of the radiobuttons.

Update

If you want to ensure you get RadioButtons with the same group, you have 2 options:

  • Get them in separate containers

  • Add the group filter to the lamdba expression, so it looks like this:

    rb => rb.Checked && rb.GroupName == "YourGroup"

Update 2

Modified the code to make it a little more fail proof by ensuring it won't fail if there's no RadioButton selected.


You may try writing down a similar method to the one below:

    private RadioButton GetSelectedRadioButton(params RadioButton[] radioButtonGroup)    {        // Go through all the RadioButton controls that you passed to the method        for (int i = 0; i < radioButtonGroup.Length; i++)        {            // If the current RadioButton control is checked,            if (radioButtonGroup[i].Checked)            {                // return it                return radioButtonGroup[i];            }        }        // If none of the RadioButton controls is checked, return NULL        return null;    }

Then, you can call the method like this:

RadioButton selectedRadio =              GetSelectedRadioButton(OneJobPerMonthRadio, TwoJobsPerMonthRadio);

It will return the selected one (if there is) and it will work for no matter how many radio buttons you have. You can rewrite the method, so that it returns the SelectedValue, if you wish.