Problem checking a radio button in code behind
Asked Answered
S

2

7

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;
}
Shrewd answered 22/2, 2011 at 14:14 Comment(0)
I
8

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;
    }
Idiot answered 22/2, 2011 at 14:25 Comment(1)
It's odd because if I have 20 radio buttons in the same configuration, they all work except the first one.Shrewd
S
7

Not sure if this is the correct way but it works

protected void ddl_Changed(object sender, EventArgs e)
    {
        if (ddl.SelectedIndex == 0)
        {
            rb1.Checked = true;
            rb2.Checked = false;
        }
        else
        {
            rb1.Checked = false;
            rb2.Checked = true;
        }
    }
Succinctorium answered 22/2, 2011 at 14:25 Comment(2)
That's the way I first thought of. Works fine until you have a lot of radiobuttons. The RadioButtonList allows you to clear all the items in one method.Idiot
I agree. After seeing your example that's the way to go for scalability.Succinctorium

© 2022 - 2024 — McMap. All rights reserved.