【问题标题】:Radio button to select one box only....ERROR单选按钮仅选择一个框....错误
【发布时间】:2014-07-23 00:37:26
【问题描述】:

以下代码有问题,因为我可以同时选择多个单选按钮.... 如何使以下代码仅选择一个单选按钮?请帮忙。

<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource_BGlist">
        <ItemTemplate> 
            <asp:RadioButton ID="Radio1" GroupName="BG_name" runat="server" Text='<%# Eval("BG_fileName") %>' />
            <asp:Label ID="BG_fileNameLabel" runat="server" Text='<%# Eval("BG_fileName") %>' />
        </ItemTemplate>

    </asp:ListView>

【问题讨论】:

标签: asp.net radio-button


【解决方案1】:

实现这一点的最简单方法是将列表视图包装在 ASP.NET 面板或 GroupBox 中,ASP 将实现您想要的分组。

如果单选按钮包含在某种中继器中,则添加面板不会将它们组合在一起。可能最好的解决方案是使用 Grebets' Answer 中建议的 RadioButtonList。

如果这不符合您的需要,您可以在创建单选按钮后使用 javascript 来更改它们。以下代码将在添加到页面底部时起作用:

<script type="text/javascript">
    var inputElements = document.getElementsByTagName("input");
    for (var inputName in inputElements) {
        var input = inputElements[inputName];
        if (input.type === "radio") {
            input.name = "Group1";
        }
    }
</script>

如果你使用 jQuery,脚本可以简化。

【讨论】:

  • Red the Panel 文档,但没有帮助....我还尝试在 ListView LayoutTemplate 中添加 Panel,但它也不起作用....
  • 您说得对,面板不起作用。在正常情况下会这样做,但看起来 ListView/repeaters 会破坏该功能。正在编辑答案...
  • 只要 RadioButton AutoPostBack 设置为 False,javascript 就可以正常工作。
  • 好吧,我很快就认为上面的 javascript 运行良好....事实上,如果 RadioButtons 嵌套在 ListView 中,它有助于选择一个单选按钮,但是它影响了我的代码。 RadioButton radioBtn = (RadioButton)itemRow.FindControl("Radio1");停止工作,我在后面的代码中找不到 Radio1。
  • 是的,这是一个非常糟糕的 hack——抱歉,它不适用于您的情况。在 HTML 中对单选按钮进行分组的唯一方法是分配 name 属性——这将破坏服务器端的 ASP.NET。您可以尝试将 Radio Button 呈现为直接 HTML 并找到另一种读取服务器端数据的方法,或者按照其他人的建议使用 RadioButtonList 代替——这可能是更好的解决方案。
【解决方案2】:

我认为最有效的方法是使用 RadioButtonList:

<asp:RadioButtonList ID="RadioButtonList1" runat="server" DataTextField="BG_fileName" DataValueField="BG_fileName" DataSourceID="SqlDataSource_BGlist">
</asp:RadioButtonList>

如果您更喜欢在代码隐藏中使用数据源(就像我一样):

public class MyClass
{
    public string BG_fileName { get; set; }

    public MyClass(string bgFileName)
    {
        BG_fileName = bgFileName;
    }
}

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {   
        RadioButtonList1.DataSource = new List<MyClass>
        {
            new MyClass("test string 1"),
            new MyClass("test string 2"),
            new MyClass("test string 3")
        };
        RadioButtonList1.DataBind();
    }
}

【讨论】:

    猜你喜欢
    • 2012-07-30
    • 1970-01-01
    • 2015-01-09
    • 2016-09-24
    • 1970-01-01
    • 2019-11-02
    • 2015-02-27
    • 1970-01-01
    • 2016-01-09
    相关资源
    最近更新 更多