Finding all controls of a specific type on a page

I was working with dynamically added TextBox controls in an unknown structure of recursively nested Repeaters the other day, and needed to loop through them after they were posted back to the server. Since I had no idea of where they were located, how many they were nor their IDs, I solved it in the simplest way that I could think of; by creating a recursive method looping through the entire page. Here is a generic version of that method created as a Control extension.

ControlExtensions.cs

public static class ControlExtensions
{
   public static IEnumerable<T> GetAllControlsOfType<T>(this Control parent) where T : Control
   {
      var result = new List<T>();
      foreach (Control control in parent.Controls)
      {
         if (control is T)
         {
            result.Add((T) control);
         }
         if (control.HasControls())
         {
            result.AddRange(control.GetAllControlsOfType<T>());
         }
      }
      return result;
   }
}

There is really nothing complicated about this. The method checks to see if the control is of the generic type T that we are looking for (14), and adds it to a collection if it is. Then if the control has any child controls (18), the method is recursively used on all of these and the result is finally compiled in to one large IEnumerable. Since the System.Web.UI.Page class itself is an instance of System.Web.UI.Control it is possible to use this directly on the Page object.

Method usage

    var allTextBoxesOnThePage = Page.GetAllControlsOfType<TextBox>();
    var allHyperLinksInControl = randomControl.GetAllControlsOfType<HyperLink>();

9 Comments

  1. Dean Brown April 29, 2013
  2. Ivan November 27, 2013
  3. Chris Emerson May 15, 2014
  4. Mohammad January 2, 2015
  5. Bhavana April 6, 2015
    • Mathias Kunto April 6, 2015
  6. Bassist November 27, 2015
  7. Aamir March 8, 2016
    • Mathias Kunto March 9, 2016