Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem checking a radio button in code behind

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;
}
like image 293
Greg Avatar asked Feb 22 '11 14:02

Greg


People also ask

How do you check if a radio button is not checked?

Using Input Radio checked property: The Input Radio checked property is used to return the checked status of an Input Radio Button. Use document. getElementById('id'). checked method to check whether the element with selected id is check or not.

How do I get the radio button checked by condition?

Trick is to bind the checked property to a boolean expression. Basically the radio button will be checked if index equals the matched value, and clicking that radio button updates it in the component.

How do I know which radio button is selected?

To check which radio button is selected in a form, we first get the desired input group with the type of input as an option and then the value of this selection can then be accessed by the val() method. This returns the name of the option that is currently selected.


1 Answers

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;
    }
like image 126
Richard Dalton Avatar answered Nov 04 '22 12:11

Richard Dalton