Dev: Overcoming the Radio Button Repeater Bug
I ran into a bug the other day, something I call the Radio Button/Repeater bug. It’s a known bug detailed in Microsoft’s KB article 316495.
In case you don’t want to read that, here’s a description of the bug:
Radio buttons on a form are supposed to be mutually exclusive. That is, when you select one of the radio buttons, the other choices are de-selected. Using ASP.NET controls, you get this behavior by giving all of the RadioButton controls the same GroupName value. The radio buttons rendered on the page will all have the same name and will behave in a mutually exclusive manner when selected.
However, that’s not true if the RadioButton controls are placed within a Repeater control. In that case, each rendered radio button is given a unique name, and because of that when one of them is selected, it has no effect on the other radio buttons even though they have the same GroupName value.
An MS employee offered a workaround that’s dependant on Javascript.
We use a lot of jQuery, so I wanted to modify this workaround to work with jQuery.
In the markup file, add this bit of Javascript and jQuery:
<script type=”text/javascript” language=”javascript”>
function SetUniqueRadioButton(strGroupName, current)
{
$(“input[name$='" + strGroupName + "']“).attr(‘checked’, false);
current.checked = true;
}
</script>
Set up the Repeater control using a RadioButton control:
<asp:Repeater ID=”rptMyRepeater” runat=”server” OnItemDataBound=”rptMyRepeater_ItemDateBound”>
<ItemTemplate>
<asp:RadioButton ID=”rbMyRadioButton” GroupName=”MyGroupName” runat=”server” />
</ItemTemplate>
</asp:Repeater>
Finally, in the code behind file:
protected void rptMyRepeater_ItemDateBound(object sender, RepeaterItemEventArgs e)
{
System.Web.UI.WebControls.RadioButton rbMyRadioButton = (System.Web.UI.WebControls.RadioButton)e.Item.FindControl(“rbMyRadioButton”);
if (rbMyRadioButton != null)
rbMyRadioButton.Attributes.Add(“onclick”, “SetUniqueRadioButton(‘MyGroupName’,this)”);
}
This workaround will allow you to have mutually exclusive radio buttons when using RadioButton controls within a Repeater control.
Popularity: unranked [?]
