Getting all children of Flowlayoutpanel in C#

喜夏-厌秋 提交于 2019-12-24 00:25:02

问题


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)
        {    
            Control c = control;

            var ls = new List<Control>();

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

            foreach (Control control1 in ls)
            {
                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.


回答1:


How about this:

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

Bear in mind that this is linear, not hierarchical, just like you're current algorithm.


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

private IEnumerable<Control> GetChildren(Control ctrl = null)
{
    if (ctrl == null) { ctrl = this.flowLayoutPanel; }
    List<Control> list = ctrl.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 ctrls = GetChildren();



回答2:


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);
}


来源:https://stackoverflow.com/questions/19232057/getting-all-children-of-flowlayoutpanel-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!