计算复选框的计数

时间:2016-04-27 13:52:53

标签: c# asp.net code-behind

我有多个单独的复选框(50)。

像这样:

<asp:CheckBox runat="server" ID="chkBirthDate" />

我需要知道用户选择了多少复选框(Count)。如果他选择了超过3个我让他通过,如果不是我给他一个错误信息。

提前致谢!

1 个答案:

答案 0 :(得分:5)

LINQ方法

您可以利用LINQ的查询功能,使用OfType<T>()方法获取所有单独的CheckBox控件,然后使用Count()调用查看实际检查的数量:

// Get the number of CheckBox Controls that are checked
var checkedBoxes = Form.Controls.OfType<CheckBox>().Count(c => c.Checked);
// Determine if your specific criteria is met
if(checkedBoxes > 3)
{
      // You shall pass!
}
else 
{
      // None shall pass
}

您需要确保通过包含以下using语句来引用LINQ以使其正常工作:

using System.Linq;

迭代循环方法

或者,您可以通过foreach循环简单地循环并相应地增加计数,如下所示:

// Store your count
var checkedBoxes = 0;
// Iterate through all of the Controls in your Form
foreach(Control c in Form.Controls)
{
    // If one of the Controls is a CheckBox and it is checked, then
    // increment your count
    if(c is CheckBox && (c as CheckBox).Checked)
    {
        checkedBoxes++;
    }
}

示例(带输出)

您可以找到a GitHub Gist that fully reproduces this here并在下面演示:

enter image description here

相关问题