In .net each ControlContainer can have its own controlcollection. That means if you are using controlcontainers such as panels on a form, you will need to loop through all containers.
Below is the code I generally use for that task, with as small extra addition that you can specify which type of control you want to get back
added 1-6-5: VS2005 (whidbey) code
Code> (doubleclick to copy)
#region
FormControls
public static ArrayList GetControls(ContainerControl cc, Type ctype)
{
ArrayList al = new ArrayList();
AddControls(ref al,cc.Controls,ctype);
return al;
}
private static void AddControls(ref ArrayList al,Control.ControlCollection cc,Type ctype)
{
foreach
(Control c in cc)
{
if
(ctype==null // ctype.IsAssignableFrom(c.GetType()))
al.Add(c);
if(c.HasChildren)
AddControls(ref al,c.Controls,ctype);
} }
public static ArrayList GetControls(ContainerControl cc)
{
return GetControls(cc,null);
}
#endregion
Since you can loop through an arraylist strongly typed, you can loop through the result with just the type you want.For example, to clear all textboxes:
Code> (doubleclick to copy)
foreach
(TextBox tb in GetControls(this,typeof(TextBox)))
tb.Clear();
or in vb.net
Code> (doubleclick to copy)
For Each tb As TextBox In GetControls(Me, GetType(TextBox))
tb.Clear()
Next
For those of you lucky enough to have vs2005:
public static Collection<ControlType> GetControls<ControlType>(ContainerControl Parent)
where ControlType:Control
{
Collection<ControlType> coll = new Collection<ControlType>();
findControls<ControlType>(coll, Parent);
return coll;
}
public static void findControls<ControlType>(Collection<ControlType> coll, Control Parent)
where ControlType : Control
{
foreach (Control c in Parent.Controls)
{
if (c is ControlType)
coll.Add(c as ControlType);
if (c.HasChildren)
findControls(coll, c);
}
}
//example call (procedure within a form):
void bla()
{
foreach (TextBox tb in GetControls<TextBox>(this))
{
//.....
}
}
. . .