Problem checking a radio button in code behind

asp.netradio-button

I have a simple ASP.NET form with a DropDownList and two RadioButtons (that both share the same GroupName).

In the SelectedIndexChanged event of the DropDownList, I set Checked=true on the two RadioButtons.

It sets the 2nd RadioButton fine, but it won't check the first one. What am I doing wrong?

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication3._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
    <form id="form1" runat="server">
        <asp:DropDownList runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddl_Changed"
            ID="ddl">
            <asp:ListItem Text="Foo" />
            <asp:ListItem Text="Bar" />
        </asp:DropDownList>
        <asp:RadioButton runat="server" ID="rb1" Text="Foo" GroupName="foobar" />
        <asp:RadioButton runat="server" ID="rb2" Text="Bar" GroupName="foobar" />
    </form>
</body>
</html>

protected void ddl_Changed(object sender, EventArgs e)
{
    if (ddl.SelectedIndex == 0)
        rb1.Checked = true; // <- Doesn't actually work
    else
        rb2.Checked = true;
}

Best Answer

It is failing because it is trying to set them both to selected which is not possible with radiobuttons in a group.

The best solution is to use a RadioButtonList:

    <asp:RadioButtonList ID="rblTest" runat="server">
        <asp:ListItem Text="Foo"></asp:ListItem>
        <asp:ListItem Text="Bar"></asp:ListItem>
    </asp:RadioButtonList>

Then set the selected item like this:

    protected void ddl_Changed(object sender, EventArgs e)
    {
        rblTest.ClearSelection();
        rblTest.SelectedIndex = ddl.SelectedIndex;
    }