gpt4 book ai didi

c# - 遍历 Form 的所有控件,甚至是 GroupBoxes 中的控件

转载 作者:IT王子 更新时间:2023-10-29 04:45:52 26 4
gpt4 key购买 nike

我想向我的 Form 上的所有文本框添加一个事件:

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

问题是它们存储在几个 GroupBox 中,而我的循环看不到它们。我可以单独循环遍历每个 GroupBox 的控件,但是否可以在一个循环中以一种简单的方式完成所有操作?

最佳答案

窗体和容器控件的 Controls 集合仅包含直接子项。为了得到所有的控件,你需要遍历控件树并递归地应用这个操作

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);
}
}
}

注意:表单也(间接地)派生自Control,所有控件都有一个Controls 集合。所以你可以在你的表单中调用这样的方法:

AddTextChangedHandler(this);

一个更通用的解决方案是创建一个扩展方法,将一个 Action 递归地应用于所有控件。在静态类(例如 WinFormsExtensions)中添加此方法:

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

静态类命名空间必须是“可见的”,即如果它在另一个命名空间中,则添加适当的 using 声明。

然后就可以这样调用了,其中this就是表单;您还可以将 this 替换为必须影响其嵌套控件的表单或控件变量:

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

关于c# - 遍历 Form 的所有控件,甚至是 GroupBoxes 中的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15186828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com