ASP.NET Is there a better way to find controls that are within other controls?

Generally I implement a “FindInPage” or recursive FindControl function when you have lots of control finding to do, where you would just pass it a control and it would recursively descend the control tree.

If it’s just a one-off thing, consider exposing the control you need in your API so you can access it directly.

public static Control DeepFindControl(Control c, string id)
{
   if (c.ID == id)
   { 
     return c;
   }
   if (c.HasControls)
   {
      Control temp;
      foreach (var subcontrol in c.Controls)
      {
          temp = DeepFindControl(subcontrol, id);
          if (temp != null)
          {
              return temp; 
          }
      }
   }
   return null;
}

Leave a Comment