本文介绍了如何检查至少一个单选按钮列表已经项选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有20 单选按钮列表个页面上。

我需要创建一个验证方法,以确保这些至少有一个单选按钮列表 S有选择的项目。

I need to create a validation method to ensure that at least one of these RadioButtonLists has an item selected.

我将需要使用这个什么样的验证?

What kind of validation would I need to use for this?

推荐答案

编辑:根据意见和澄清问题,更新

Updated question based on comments and clarification.

如果您要验证针对多个单选按钮列表 s然后需要使用的CustomValidator 并实现服务器端检查

If you are validating against multiple RadioButtonLists then you need to use a CustomValidator and implement the server side check.

下面是一些测试标记:

<asp:RadioButtonList ID="rblstTest1" runat="server" ValidationGroup="Test">
    <asp:ListItem Text="Test 1" Value="1" />
    <asp:ListItem Text="Test 2" Value="2" />
    <asp:ListItem Text="Test 3" Value="3" />
</asp:RadioButtonList>
<br /><br />
<asp:RadioButtonList ID="rblstTest2" runat="server" ValidationGroup="Test">
    <asp:ListItem Text="Test 1" Value="1" />
    <asp:ListItem Text="Test 2" Value="2" />
    <asp:ListItem Text="Test 3" Value="3" />
</asp:RadioButtonList><br />
<asp:Button ID="btnTestRb" runat="server" ValidationGroup="Test" Text="Test RBL" 
    OnClick="btnTestRb_Click" />
<asp:CustomValidator runat="server" ValidationGroup="Test" ID="cvTest" 
    ControlToValidate="rblstTest1" OnServerValidate="cvTest_ServerValidate" 
    ValidateEmptyText="true" Enabled="true" display="Dynamic" SetFocusOnError="true"
    ErrorMessage="You must select at least one item." /> 

使用下面的扩展方法来发现所有的单选按钮列表控件(来源

Use the following extension method to find all the RadioButtonList controls (Source):

static class ControlExtension
{
    public static IEnumerable<Control> GetAllControls(this Control parent)
    {
        foreach (Control control in parent.Controls)
        {
            yield return control;
            foreach (Control descendant in control.GetAllControls())
            {
                yield return descendant;
            }
        }
    }
} 

然后实现服务器端的CustomValidator 检查:

protected void cvTest_ServerValidate(object sender, ServerValidateEventArgs e)
{            
    int count = this.GetAllControls().OfType<RadioButtonList>().
        Where(lst => lst.SelectedItem != null).Count();
    e.IsValid = (count > 0);
 }

我已经测试上面的例子中,它似乎做的正是你所需要的。你应该能够将其轻松地切换到VB pretty。希望这会解决您的问题。

I have tested the above example and it seems to do exactly what you need. You should be able to switch it to VB pretty easily. Hope this solves your problem.

这篇关于如何检查至少一个单选按钮列表已经项选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!