C# Recursively Find an ASP.net Control

Finds a control within the current page which is of a specific type and has a specific Id.

    public T FindControlById(string id) where T : Control
{
  return FindControlByTypeAndId(Page, id);
}

Finds a control within a specified ASP.net control which is of a specific type and has a specific Id.

    public static T FindControlByTypeAndId(Control startingControl, string id) where T : Control
    {
      // this is null by default
      T found = default(T);

      int controlCount = startingControl.Controls.Count;

      if (controlCount > 0)
      {
        for (int i = 0; i < controlCount; i++)
        {
          Control activeControl = startingControl.Controls[i];
          if (activeControl is T)
          {
            found = startingControl.Controls[i] as T;
            if (string.Compare(id, found.ID, true) == 0) break;
            found = null;
          }
          else
          {
            found = FindControlByTypeAndId(activeControl, id);
            if (found != null) break;
          }
        }
      }
      return found;
    }

Finds a list of controls within a specified ASP.net Control which are of a specific type

    public static List FindControlsByType(Control startingControl) where T : Control
    {
      // Container for storing all located controls of Type T
      List found = new List();

      //See how many controls are in the collection
      int controlCount = startingControl.Controls.Count;
      if (controlCount > 0)
      {
        for (int i = 0; i < controlCount; i++)
        {
          Control activeControl = startingControl.Controls[i];
          if (activeControl is T)
          {
            found.Add(startingControl.Controls[i] as T);
          }
          else
          {
            found.AddRange(FindControlsByType(activeControl));
          }
        }
      }
      return found;
    }

Published by

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s