Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all children of a parent control?

Tags:

c#

.net

controls

I'm looking for an code example how to get all children of parent control.

I have no idea how do it.

foreach (Control control in Controls)
{
  if (control.HasChildren)
  {
    ??
  }
}
like image 300
The Mask Avatar asked Dec 21 '11 19:12

The Mask


1 Answers

If you only want the immediate children, use

...
var children = control.Controls.OfType<Control>();
...

If you want all controls from the hierarchy (ie, everything in the tree under a certain control), use a pretty simple data-recursive method:

    private IEnumerable<Control> GetControlHierarchy(Control root)
    {
        var queue = new Queue<Control>();

        queue.Enqueue(root);

        do
        {
            var control = queue.Dequeue();

            yield return control;

            foreach (var child in control.Controls.OfType<Control>())
                queue.Enqueue(child);

        } while (queue.Count > 0);

    }

Then, you might use something like this in a form:

    private void button1_Click(object sender, EventArgs e)
    {
        /// get all of the controls in the form's hierarchy in an IEnumerable<>
        foreach (var control in GetControlHierarchy(this))
        {
            /// do something with this control
        }
    }
like image 83
3Dave Avatar answered Sep 28 '22 03:09

3Dave