Loop through all controls on asp.net webpage

Solution 1:

I rather like David Finleys linq approach to FindControl http://weblogs.asp.net/dfindley/archive/2007/06/29/linq-the-uber-findcontrol.aspx

public static class PageExtensions
{
    public static IEnumerable<Control> All(this ControlCollection controls)
    {
        foreach (Control control in controls)
        {
            foreach (Control grandChild in control.Controls.All())
                yield return grandChild;

            yield return control;
        }
    }
}

Usage:

// get the first empty textbox
TextBox firstEmpty = accountDetails.Controls
    .All()
    .OfType<TextBox>()
    .Where(tb => tb.Text.Trim().Length == 0)
    .FirstOrDefault();

// and focus it
if (firstEmpty != null)
    firstEmpty.Focus();

Solution 2:

Your original method will not work if you start from the root element of your document: something like page.Controls as you will only loop through the first level of controls, but remember a control can be composite. So you need recursion to pull that off.

        public void FindTheControls(List<Control> foundSofar, Control parent) 
        {

            foreach(var c in parent.Controls) 
            {
                  if(c is IControl) //Or whatever that is you checking for 
                  {

                      foundSofar.Add(c);

                      if(c.Controls.Count > 0) 
                      {
                            this.FindTheControls(foundSofar, c);
                      }
                  }


            }  

        }

Solution 3:

foreach (Control ctlMaster in Page.Controls)
{
    if (ctlMaster is MasterPage)
    {
        foreach (Control ctlForm in ctlMaster.Controls)
        {
            if (ctlForm is HtmlForm)
            {
                foreach (Control ctlContent in ctlForm.Controls)
                {
                    if (ctlContent is ContentPlaceHolder)
                    {
                        foreach (Control ctlChild in ctlContent.Controls)
                        {
                            //Do something!
                        }
                    }
                }
            }
        }
    }
}

This should do it. Though you might need to do some checking to make sure you're actually dealing with the correct ContentPlaceHolder if there's more than one.