Get available controls from a Form

前端 未结 3 397
粉色の甜心
粉色の甜心 2020-12-10 23:46

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

相关标签:
3条回答
  • 2020-12-11 00:00

    Or, ProfK's solution in enumerable syntax:

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-11 00:01

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

    foreach(Control c in this.Controls)
    {
       //TODO:
    }
    
    0 讨论(0)
  • 2020-12-11 00:13

    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);
    
    0 讨论(0)
提交回复
热议问题