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:
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?
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()));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With