检查是否选中了表单的所有复选框 [英] Check if all checkboxes of form are checked

查看:26
本文介绍了检查是否选中了表单的所有复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从代码中动态创建了多个复选框,所以我知道我可以使用以下方法获取复选框:

I have multiple checkboxes that I created dinamically from code, So I know I can get checkboxes using:

foreach (var checkBox in this.Controls.OfType<CheckBox>())
            {

            }

但是我想知道或者我想要的结果是知道我的表单中的所有复选框是否都被选中,比如如果所有复选框都被选中则返回 true 或者如果缺少一个则返回 false ......我怎么能做到这一点?问候

But that I want to know or my desire result is to know if all checkboxes of my form are checked something like a bool returning true if all checkboxes are checked or false if one is missing... How can I achieve that? Regards

bool allChecked = ... 

推荐答案

如果你想验证表单上的所有复选框都被选中,即使是那些属于其他容器控件的复选框,你将不得不遍历每个控件的 Controls 集合(不仅仅是属于 Form 的那些).

If you want to verify that all checkboxes on the form are checked, even those that belong to other container controls, you will have to iterate over each control's Controls collection (not just those belonging to the Form).

实现此目的的一种方法是编写一个递归方法,该方法接收容器控件(如 Form)并检查其集合中的所有控件.如果任何包含的控件是 Checkbox 并且未选中,则返回 false.否则,对该控件的 Controls 集合执行递归检查.如果这些检查都不为假,则返回真.

One way to do this is to write a recursive method that takes in a container control (like the Form) and examines all the controls in it's collection. If any contained control is a Checkbox and it isn't checked, then return false. Otherwise, perform a recursive check on that control's Controls collection. If neither of these checks is false, then return true.

例如:

private static bool ContainedCheckboxesAreChecked(Control containerControl)
{        
    // For each control in the container
    foreach (Control control in containerControl.Controls)
    {
        // Return false if the control is a checkbox and it's not checked
        if (!(control as CheckBox)?.Checked ?? false) return false;

        // Do a recursive check on this control's Controls collection
        if (!ContainedCheckboxesAreChecked(control)) return false;
    }

    // If we got this far, return true
    return true;
}

现在,如果你调用这个并将主窗体作为容器控件传入,你将检查窗体上的所有控件,包括所有容器(甚至嵌套容器):

Now, if you call this and pass in the main form as the container control, you will examine all controls on the form, including in all containers (even nested containers):

bool allCheckBoxesAreChecked = ContainedCheckboxesAreChecked(this);

这篇关于检查是否选中了表单的所有复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆