Dimo
Dimo

Reputation: 3290

Getting all children of Flowlayoutpanel in C#

I have a Flowlayoutpanel with an unknown amount of children. How can I retrieve all the children? So far I have tried this with no success:

private LoopReturn(Control control)
{    
    var c = control;

    var list = new List<Control>();

    while (c != null)
    {
        list.Add(c);
        c = c.GetNextControl(c, true);                    
    }

    foreach (var control1 in list)
        Debug.Print(control.Name);  
}

But I'm only getting the first two children. Does anybody know why?

EDIT:

I need to the children of all children of all children etc.

Upvotes: 2

Views: 7584

Answers (2)

Mike Perrenoud
Mike Perrenoud

Reputation: 67948

How about this:

var controls = flowLayoutPanel.Controls.OfType<Control>();

Bear in mind that this is linear, not hierarchical, just like your current algorithm.


To get the all children, regardless of level, you'd need to do something like this:

private IEnumerable<Control> GetChildren(Control control = null)
{
    if (control == null) control = flowLayoutPanel;

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

    foreach (var child in list)
        list.AddRange(GetChildren(child));

    return list;
}

and then when you want the overall list just do this:

var controls = GetChildren();

Upvotes: 2

LarsTech
LarsTech

Reputation: 81675

A recursive function would work:

private IEnumerable<Control> ChildControls(Control parent) {
  List<Control> controls = new List<Control>();
  controls.Add(parent);
  foreach (Control ctrl in parent.Controls) {
    controls.AddRange(ChildControls(ctrl));
  }
  return controls;
}

Then to call it:

foreach (Control ctrl in ChildControls(flowLayoutPanel1)) {
  Debug.Print(ctrl.Name);
}

Upvotes: 1

Related Questions