通过表单上的所有控件,甚至没有在groupboxes环 [英] Loop through all controls on a form,even those in groupboxes

查看:131
本文介绍了通过表单上的所有控件,甚至没有在groupboxes环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将事件添加到我的窗体上的所有文本框:

I'd like to add an event to all textboxes on my form:

foreach (Control C in this.Controls)
{
    if (C.GetType() == typeof(System.Windows.Forms.TextBox))
    {
        C.TextChanged += new EventHandler(C_TextChanged);
    }
}



的问题是,它们存储在若干groupboxes和我的循环不会看到它们。我可以遍历单独但是每个组框控件是有可能做到这一切在一个简单的方法在一个循环?

The problem is that they are stored in several groupboxes and my loop doesn't see them. I could loop through controls of each groupbox individually but is it possible to do it all in a simple way in one loop?

推荐答案

控件集合包含只顾眼前的孩子。为了让所有的控制,你需要遍历控件树,并应用该操作递归

The Controls collection contains only the immediate children. In order to get all the controls, you need to traverse the controls tree and to apply this operation recursively

private void AddTextChangedHandler(Control parent)
{
    foreach (Control c in parent.Controls)
    {
        if (c.GetType() == typeof(TextBox)) {
            c.TextChanged += new EventHandler(C_TextChanged);
        } else {
            AddTextChangedHandler(c);
        }
    }
}



注:形式提炼出来(间接)从控制以及和所有控件有一个控制集合。所以,你可以这样调用该方法在您的形式:

Note: The form derives (indirectly) from Control as well and all controls have a Controls collection. So you can call the method like this in your form:

AddTextChangedHandler(this);






一个更通用的解决方案是创建一个扩展该递归的应用一个动作的所有控件的方法。在静态类(如 WinFormsExtensions )添加这个方法:

public static void ForAllControls(this Control parent, Action<Control> action)
{
    foreach (Control c in parent.Controls) {
        action(c);
        ForAllControls(c, action);
    }
}



静态类的命名空间必须是看得见,即,添加适当的使用声明,如果它是另一个命名空间。

The static classes namespace must be "visible", i.e., add an appropriate using declaration if it is in another namespace.

然后,你可以这样调用它,在那里这个的形式;你也可以替换这个表格或控制变量,其嵌套控件都将受到影响:

Then you can call it like this, where this is the form; you can also replace this by a form or control variable whose nested controls have to be affected:

this.ForAllControls(c =>
{
    if (c.GetType() == typeof(TextBox)) {
        c.TextChanged += C_TextChanged;
    }
});

这篇关于通过表单上的所有控件,甚至没有在groupboxes环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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