Code:
public static IEnumerable<Control> GetAllControls(this Control Parent, System.Type Type = null)
{
if (Parent == null)
{
yield break;
}
if (Type == null || Parent.GetType().Equals(Type))
{
yield return Parent;
}
foreach (Control Control in Parent.Controls)
{
foreach (Control x in Control.GetAllControls(Type))
{
yield return x;
}
}
}
Example usage:
List<Control> PageControls = Page.GetAllControls().ToList();
IEnumerable<Control> DropDownLists = Page.GetAllControls(typeof(DropDownList));

It would be better to use LINQ to limit the types: Page.GetAllControls().OfType(); It requires just a couple of extra characters, and will be more recognizable.
ReplyDeleteI agree, thanks for pointing that out.
ReplyDelete