One technique I've seen is to create an extension method on ControlCollection that returns an IEnumerable ... something like this:
public static IEnumerable<Control> FindAll(this ControlCollection collection)
{
foreach (Control item in collection)
{
yield return item;
if (item.HasControls())
{
foreach (var subItem in item.Controls.FindAll())
{
yield return subItem;
}
}
}
}
That handles the recursion. Then you could use it on your page like this:
var textboxes = this.Controls.FindAll().OfType<TextBox>();
which would give you all the textboxes on the page. You could go a step further and build a generic version of your extension method that handles the type filtering. It might look like this:
public static IEnumerable<T> FindAll<T>(this ControlCollection collection) where T: Control
{
return collection.FindAll().OfType<T>();
}
and you could use it like this:
var textboxes = this.Controls.FindAll<TextBox>().Where(t=>t.Visible);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…