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

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


item name 2

Price: €20.00



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

Share this post

blog comments powered by Disqus


Follow me online at TwitterFacebook or Flickr. If you want to get in touch with me try emailing me.

Latest Tweets