A Better FindControl Method

For ASP.NET web forms developers, this is a handy extension method of the Control class that returns a strongly-typed control instance from a deep recursive search at any point in the control tree hierarchy:

public static partial class ControlExtensions
    public static T FindControl<T>(this Control currentControl, string id) where T : Control
        if (id.Equals(currentControl.ID, StringComparison.OrdinalIgnoreCase))
            // return control calling this method
            return currentControl as T;
        // initialize potential "found" control to null
        T potentialFoundControl = null;

        foreach (Control childControl in currentControl.Controls)
            // recursive call to each child control  
            potentialFoundControl = ControlExtensions.FindControl<T>(childControl, id);
            // if result is not null, match has been found, break the loop
            if (potentialFoundControl != null) { break; }
        return potentialFoundControl;
    }// method
}// class

Comments (1)

Skip to main content