Monday, October 5, 2009

A recursive FindControl extension method

The System.Web.UI.Control class has a FindControl method for finding a control by its ID. This method searches for a given control in the first level child controls, and not in any child controls of a child. In order to do the latter, a custom method must be implemented. Below is a generic, recursive, extension method that does this:


public static class ControlExtension
{
 public static T FindControlRecursive(this Control container, string id)
   where T : Control
 {   
  if (container.HasControls())
  {
   T foundControl = null;

   foreach (Control control in container.Controls)
   {
    if (control.ID == id && control is T)
     foundControl = (T) control;
    else
     foundControl = FindControlRecursive(control, id);

    if (foundControl != null)
     return foundControl;
   }
  }

  return null;
 }
}

Usage:


var control = Page.FindControlRecursive("TxtName");