Gre*_*reg 7 asp.net radio-button
我有一个简单的ASP.NET表单,带有DropDownList和两个RadioButtons(两者都共享相同的GroupName).
在DropDownList的SelectedIndexChanged事件中,我设置Checked=true了两个RadioButtons.
它设置第二个RadioButton很好,但它不会检查第一个.我究竟做错了什么?
<%@ 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;
}
Run Code Online (Sandbox Code Playgroud)
它失败了,因为它试图将它们都设置为选中,这对于组中的无线电按钮是不可能的.
最好的解决方案是使用RadioButtonList:
<asp:RadioButtonList ID="rblTest" runat="server">
<asp:ListItem Text="Foo"></asp:ListItem>
<asp:ListItem Text="Bar"></asp:ListItem>
</asp:RadioButtonList>
Run Code Online (Sandbox Code Playgroud)
然后像这样设置所选项目:
protected void ddl_Changed(object sender, EventArgs e)
{
rblTest.ClearSelection();
rblTest.SelectedIndex = ddl.SelectedIndex;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
不确定这是否是正确的方法,但它的工作原理
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26862 次 |
| 最近记录: |