I have been pondering how I can get all controls on a page and then perform a task on them in this related question:
How to Search Through a C# DropDownList Programm
Had this very question and while I found Steve B's answer useful, I wanted an extension method, so re-factored it:
public static IEnumerable<T> GetControlList<T>(this ControlCollection controlCollection) where T : Control
{
foreach (Control control in controlCollection)
{
if (control is T)
{
yield return (T)control;
}
if (control.HasControls())
{
foreach (T childControl in control.Controls.GetControlList<T>())
{
yield return childControl;
}
}
}
}
var dropDownLists = new List<DropDownList>();
foreach (var control in this.Controls)
{
if (control is DropDownList)
{
dropDownLists.Add( (DropDownList)control );
}
}