I got a simple "mission" to make a method that collect all the TextBox controls from any given control on the page (or from the Page itself). As I like to do things in the most 'Generic' way, I finished with a simple method that collect all contols from any type you want.
This is the method that run recursive and collect all the controls from type T:
/// <summary>
/// Loot recursive and collect the controls
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="contol"></param>
/// <param name="list"></param>
private static void LoopControls<T>(Control parentContol, List<T> list) where T : Control
{
foreach (Control ctrl in parentContol.Controls)
{
if (ctrl is T)
{
list.Add(ctrl as T);
}
else
{
if (ctrl.Controls.Count > 0)
{
LoopControls(ctrl, list);
}
}
}
}
To start the 'collecting' process:
/// <summary>
/// Collect all the controls from type 'T'
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="contol"></param>
/// <returns></returns>
public static List<T> CollectControls<T>(Control parent) where T : Control
{
List<T> list = new List<T>();
LoopControls(parent, list);
return list;
}
Drop this method in your 'Utilities' class, and its ready to go. Now, To collect all the TextBox in the page, just us it like this:
System.Collections.Generic.List<TextBox> l = Utils.CollectControls<TextBox>(Page);
and to collect all the Labels, just change the '<TextBox>' to '<Label>'.
Using 'Generic' is very goot thing, and a lot of times, if you thing on the feutre and not focus only on the current mission when you write any method, you will end up using the Generic namespace.