I came across a need the other day to recurse the page control tree (or any control tree really) to find all controls of a certain type, so this is the extension method I wrote to help me do that. Hopefully it will help others as well.
/// <summary>
/// Recurses the control tree and finds all controls in the control collection that are of the specified type.
/// </summary>
/// <typeparam name="T">The type of control you want to find</typeparam>
/// <param name="controls">The controls.</param>
/// <returns></returns>
public static IEnumerable<T> FindRecursive<T>(this ControlCollection controls)
{
// create list of results
List<T> results = new List<T>();
// add controls in current control collection that match type
results.AddRange(controls.OfType<T>());
// recurse control tree
foreach (Control c in controls)
{
// add controls to results
results.AddRange(FindRecursive<T>(c.Controls));
}
return results;
}
This method could easily be extended to accept another parameter to specify the ID of the control. The method above does depend on System.Linq and .NET 3.5 (or at least visual studio 2008, because I believe that most of this is just a compiler trick).