aron aron - 11 days ago 4
ASP.NET (C#) Question

foreach Control ctrl in SomePanel.Controls does not get all controls

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!

Answer

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.

Comments