asp.net - 在后面的代码中检查单选按钮时出现问题

标签 asp.net radio-button

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

在 DropDownList 的 SelectedIndexChanged 事件中,我设置了 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;
}

最佳答案

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

最好的解决方案是使用 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;
    }

关于asp.net - 在后面的代码中检查单选按钮时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5079237/

相关文章:

c# - 在 ASP.NET MVC 中更改 View 的布局(母版页)而不重新创建它

asp.net - Blazor WASM 授权不适用于 AAD 角色

c# - 跟踪 Visual Studio 中的错误

javascript - 将单选按钮绑定(bind)到对象数组

c# - 您尝试打开的文件 'file.xls' 的格式与文件扩展名指定的格式不同

php - 单选按钮名称属性可以有数值吗

android - 如何更改布局上 RadioGroup 的大小?

Javascript 单选按钮值返回未定义

javascript - 合并文本区域中选定单选按钮和复选框的值

c# - 当 C# 超出范围时,C# 是否自动将 "dispose"IDisposable 对象?