问题
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