【问题标题】:Get available controls from a Form从表单获取可用控件
【发布时间】:2009-03-17 07:22:45
【问题描述】:

如何使用 C# 从Windows Forms 表单获取可用控件?

【问题讨论】:

  • “可用”是什么意思?
  • 我希望你们能花一分钟时间思考如何表达您的问题,而不是一想到就点击提交。你知道,我们这里不是心灵感应器。
  • @Cerebrus:我同意这个问题的质量真的很糟糕,但是有很多人的英语水平很差,以至于用字典写一个这样的问题可能需要半个小时在手里。伤心,我知道。
  • @Ravi:也许您想在 Visual Studio 工具箱中获得可用的设计时控件?

标签: c# winforms


【解决方案1】:

或者,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;
    }
}

【讨论】:

  • 任何将包括菜单项以及(不是控件)但仍然?
【解决方案2】:

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

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

然后用一个:

List<Control> availControls = GetControls(this);

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 对于作为其他控件容器的任何子控件,这必须是递归的。
    猜你喜欢
    • 2014-01-21
    • 1970-01-01
    • 2013-11-10
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多