c# - 如何在 Windows 窗体中获取窗体的所有控件?

标签 c# winforms forms

我有一个名为 AForm

A 包含许多不同的控件,包括一个主要的 GroupBox。此 GroupBox 包含许多表格和其他 GroupBox。我想找到一个控件,例如A 中的选项卡索引 9,但我不知道哪个 GroupBox 包含此控件。

我该怎么做?

最佳答案

递归...

public static IEnumerable<T> Descendants<T>( this Control control ) where T : class
{
    foreach (Control child in control.Controls) {

        T childOfT = child as T;
        if (childOfT != null) {
            yield return (T)childOfT;
        }

        if (child.HasChildren) {
            foreach (T descendant in Descendants<T>(child)) {
                yield return descendant;
            }
        }
    }
}

您可以像这样使用上面的函数:

var checkBox = (from c in myForm.Descendants<CheckBox>()
                where c.TabIndex == 9
                select c).FirstOrDefault();

这将在 TabIndex 为 9 的表单中的任何位置获得第一个 CheckBox。显然,您可以使用任何您想要的标准。

如果您不是 LINQ 的粉丝查询语法,上面可以重写为:

var checkBox = myForm.Descendants<CheckBox>()
                     .FirstOrDefault(x=>x.TabIndex==9);

关于c# - 如何在 Windows 窗体中获取窗体的所有控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2735190/

相关文章:

c# - 哪个更好 lambda 表达式或

c# - 将 IConfiguration 注入(inject)到 .NET 6.0 上的 Windows 窗体

javascript - 如何为禁用的 HTML 输入文本字段启用 HTML 验证

php - 腾出空间

php - 使用表单上的 php/mysql 数据库查询和单选按钮进行实时刷新

c# - 使用 LINQ 将 DataRow 转换为字典

c# - 在运行时加载 "loose"本地化资源?

c# - UOM(度量单位)设计模式

c# - 确定列表框项目的来源

winforms - 你如何处理 Winforms 中临时无用的控件(隐藏与禁用)?