views:

21

answers:

2

I'm trying to enumerate through all the Controls of a Page, but all I can find is thePage.FindControl(string) and the .Controls property doesn't has the controls that I have on the page. Anybody knows how to enumerate through all the controls of a web-forms page

+1  A: 

The Controls property only contains the direct children of the current control. If you want to iterate through all the controls on the page, you'll have to iterate through the page's children, then recursively iterate through their children, and then their childrens' children et cetera. A recursive method is the most straightforward way to implement this.

Matti Virkkunen
+2  A: 

The following should enumerate all the child controls for you.

IEnumerable<Control> GetAllChildControls(ControlCollection controls)
{
  foreach(Control c in controls)
  {
    yield return c;

    if(c.Controls.Count > 0)
    {
      foreach(Control control in GetAllChildControls(c.Controls))
      {
        yield return control;
      }
    }
  }
}
ScottS