Monday, October 08, 2007

Find and get list of controls on page

If you want to find list of controls on Page you can use this method:
private List<T> GetControls<T>() where T:Control
{
List<T> list = new List<T>();
foreach (Control rootControl in Controls)
{
foreach (Control control in rootControl.Controls)
{
if (control as T != null)
{
list.Add(control as T);
}
}
}
return list;
}
And a using is very simple. In example you can see how to change background to all labels:
List<Label> list = 
GetControls<Label>();
list.ForEach(
delegate (Label lab)
{
lab.BackColor =
System.Drawing.Color.Pink;
}
);

 


kick it on DotNetKicks.com

1 comment:

Anonymous said...

Hi, how deep will this work? I notice you only have 2 loops, what about recursion? - just food for thought.