计算选中复选框的数量

Count number of checkbox checked

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

像这样:

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

我需要知道用户选中了多少个复选框(计数)。如果他选择了超过 3 个,我会让他通过,如果没有,我会向他显示错误消息。

提前致谢!

LINQ 方法

您可以利用 LINQ 的查询功能,使用 OfType<T>() method to grab all of your individual CheckBox Controls and then use a 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 并在下面进行演示: