C# 从表单获取可用控件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/653284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:57:37  来源:igfitidea点击:

Get available controls from a Form

c#winforms

提问by Ravi

How do I get available controls from a Windows Formsform using C#?

如何使用 C#从Windows 窗体窗体获取可用控件?

回答by Ahmed Said

I think you mean all controls on the form. So simply you can use Controlsproperty inside your form object.

我认为您的意思是表单上的所有控件。因此,您可以Controls在表单对象中使用属性。

foreach(Control c in this.Controls)
{
   //TODO:
}

回答by ProfK

Try this method in your form. It will recursively get all controls on your form, and their children:

在您的表单中尝试此方法。它将递归地获取您的表单及其子项上的所有控件:

public static List<Control> GetControls(Control form)
{
    var controlList = new List<Control>();

    foreach (Control childControl in form.Controls)
    {
        // Recurse child controls.
        controlList.AddRange(GetControls(childControl));
        controlList.Add(childControl);
    }
    return controlList;
}

Then call it with a:

然后用一个调用它:

List<Control> availControls = GetControls(this);

回答by erikkallen

Or, ProfK's solution in enumerable syntax:

或者,ProfK 的可枚举语法解决方案:

public static IEnumerable<Control> GetControls(Control form) {
    foreach (Control childControl in form.Controls) {   // Recurse child controls.
        foreach (Control grandChild in GetControls(childControl)) {
            yield return grandChild;
        }
        yield return childControl;
    }
}