Loop through all radio buttons in your form using C#

There have been times when making forms with radio buttons that I have used ASP:RadioButtonLists but recently I was working on a project that required me to have a lot of radio buttons on screen within a nicely styled grid. I could have taken the easy (but messy) way out and simply done an 'if statement' to check through each radio button but that would have been impractical because of the number of radio buttons on the page. I also didn't want to hard code any radio button names because that would have been too messy to manage going forward.

What I decided to do was setup a control box around my groups of radio buttons and then use a for loop to loop through all of the radio buttons to see what one was checked before passing to the next page. Below is the html and C# code I used to accomplish this task. It's a nice and quick way of looping through radio buttons on your form. I have just used generic naming below, obviously you should always name your controls with proper meaningful names ;)

HTML:
If you have different groupings of radio buttons then be sure to wrap your radio button groups within an ASP:Panel. This will allow you to target just those radio buttons within that group to check which items were selected.


item name 1

Price: €10.00

link

item name 2

Price: €20.00

link

C# CODE:

foreach (Control SelectedButton in Panel1.Controls)
{
  if (SelectedButton is RadioButton)
  {
    if (((RadioButton)SelectedButton).Checked)
    {
      string RadioButtonSelected = SelectedButton.ID;
      break;
    }
  }
}

blog comments powered by Disqus

Get In Touch

Follow me online at TwitterFacebook or Flickr.

Latest Tweets