aron aron - 1 year ago 85
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?


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download