How to Traverse the Control Tree in Asp.Net with C# 2.0
I couldn't find any easy way to traverse the entire asp .net control tree using the framework classes, so I decided to write my own implementation. In the end, I wanted to be able to traverse all of the controls and get all which are of a certain type. First, the method which traverses the tree:
public static void RecurseControls(ControlCollection controls, FindControlDelegate callback)
{
foreach (Control c in controls)
{
callback(c);
if (c.Controls.Count > 0)
{
RecurseControls(c.Controls, callback);
}
}
}
This basically recurses through the control tree and calls a given delegate for each control found. Here is the delegate:
public delegate void FindControlDelegate(Control control);
To top it all off, here is the method I wrote to find all of the controls of a given type on a page:
public static List<T> FindAllControls<T>(Page page)
where T : Control
{
List<T> controls = new List<T>();
RecurseControls(page.Controls, delegate(Control c)
{
if(c is T)
controls.Add(c as T);
});
return controls;
}
I am usually not one to use cryptic programming techniques such as inline delegates, but in this case it just made sense. Otherwise, I would have had to somehow share the object containing the list of found controls between two different methods.