Reputation: 16690
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;
}
Upvotes: 7
Views: 30133
Reputation: 349
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;
}
}
Upvotes: 7
Reputation: 35803
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;
}
Upvotes: 8