views:

164

answers:

4

Hello, I have a panel with a bunch of labeles and textboxes inside of it.

The code:

foreach (Control ctrl in this.pnlSolutions.Controls)

Seems to only be finding html table inside the panel and 2 liternals. But it does not get the textboxes that are in the html table. Is there a simple way to get all the controls inside of a panel regardless of the nesting?

thanks!

+4  A: 

You would need to recursively "treewalk" through the controls, think about it like walking through a folder structure.

there is a sample Here

Yoda
+1, I would do just that.
Radoslav Hristov
+2  A: 

As far as I know your have to implement the recursion yourself, but its not really difficult.

A sketch (untested):

void AllControls(Control root, List<Control> accumulator)
{
    accumulator.Add(root);
    foreach(Control ctrl in root.Controls)
    {
        AllControls(ctrl, accumulator);
    }
}
Grzenio
+1  A: 

The reason is because the only controls that are direct children of your panel are the table and the literals you mention, and it is only these that this.pnlSolutions.Controls returns.

The text boxes an labels are child controls of the table, making them grandchildren of the panel.

As @Yoda points out you need to recursively walk the controls to find them all.

ChrisF
+4  A: 

Here's a lazy solution:

public IEnumerable<Control> GetAllControls(Control root) {
  foreach (Control control in root.Controls) {
    foreach (Control child in GetAllControls(control)) {
      yield return child;
    }
  }
  yield return root;
}

Remember also that some controls keep an internal collection of items (like the ToolStrip) and this will not enumerate those.

Ron Warholic
luvs me a lazy solution :)Thanks this worked perfectly!I never heard of "yield" before :)
aron