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.
<asp:panel id="Panel1" runat="server">
<table border="0">
<tbody>
<tr>
<td width="40"><input type="radio" name="button1" groupname="RadioGroup"></td>
<td class="text">
<h4>item name 1</h4>
<p>
Price: €10.00
</p>
</td>
<td width="140"><a href="#">link</a></td>
</tr>
<tr>
<td width="40"><input type="radio" name="button2" groupname="RadioGroup"></td>
<td class="text">
<h4>item name 2</h4>
<p>
Price: €20.00
</p>
</td>
<td width="140"><a href="#">link</a></td>
</tr>
</tbody>
</table>
</asp:panel>
C#
foreach (Control SelectedButton in Panel1.Controls)
{
if (SelectedButton is RadioButton)
{
if (((RadioButton)SelectedButton).Checked)
{
string RadioButtonSelected = SelectedButton.ID;
break;
}
}
}
Member discussion