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;
    }

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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s