Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Control.Controls property return recursively nested controls?

Tags:

c#

winforms

The MSDN documentation for System.Windows.Forms.Control.Controls property (for example, here) states:

Use the Controls property to iterate through all controls of a form, including nested controls.

I'm at a loss as for what does "nested controls" properly mean here.
To illustrate an issue, I made a form, consisting of:

  • a button
  • a ListBox
  • a groupbox with a button inside.

The code

MessageBox.Show(Controls.Count.ToString());

yields the answer 3. Based on my understanding of the docs, I have assumed it would provide 4 instead (counting the button inside the groupbox). The same behavior is observed if the groupbox is replaced by the panel.

What does the aforementioned phrase about nested controls actually mean?

like image 750
alexdelphi Avatar asked Sep 15 '25 01:09

alexdelphi


1 Answers

Control.Controls is a collection of that control's immediate children. Therefore your form's Controls collection will have 3 controls. And your GroupBox's Controls collection will have 1 control (the button).

I'm not really sure what that comment in the documentation was getting at, aside from perhaps (although not so eloquently) hinting that you can use this property recursively to get at all nested controls. For example:

static IEnumerable<Control> GetAllDescendantControls(this Control c)
{
    return c.Controls.Cast<Control>()
        .Concat(c.Controls.SelectMany(x => x.GetAllDescendantControls()));
}
like image 198
lc. Avatar answered Sep 17 '25 16:09

lc.