【问题标题】:Problem checking a radio button in code behind检查代码后面的单选按钮时出现问题
【发布时间】:2011-07-02 01:01:57
【问题描述】:

我有一个简单的 ASP.NET 表单,其中包含一个 DropDownList 和两个 RadioButtons(它们共享相同的 GroupName)。

在 DropDownList 的 SelectedIndexChanged 事件中,我在两个 RadioButtons 上设置了Checked=true

它设置第二个 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;
}

【问题讨论】:

    标签: asp.net radio-button


    【解决方案1】:

    它失败了,因为它试图将它们都设置为选中,这对于组中的单选按钮是不可能的。

    最好的解决方案是使用 RadioButtonList:

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

    然后像这样设置选中的项目:

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

    【讨论】:

    • 这很奇怪,因为如果我在相同的配置中有 20 个单选按钮,除了第一个之外,它们都可以工作。
    【解决方案2】:

    不确定这是否是正确的方法,但它有效

    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;
            }
        }
    

    【讨论】:

    • 这就是我最初想到的方式。工作正常,直到你有很多单选按钮。 RadioButtonList 允许您在一种方法中清除所有项目。
    • 我同意。在看到您的示例之后,这就是实现可扩展性的方法。
    猜你喜欢
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 2015-05-21
    • 2014-05-14
    • 2014-09-13
    • 1970-01-01
    • 2017-11-17
    • 2018-10-13
    相关资源
    最近更新 更多