Flattening System.Web.UI ControlCollection
Posted
by evovision
on ASP.net Weblogs
See other posts from ASP.net Weblogs
or by evovision
Published on Wed, 12 May 2010 13:24:00 GMT
Indexed on
2010/05/12
13:55 UTC
Read the original article
Hit count: 193
Hi,
Sometimes one may need to get a list of child controls inside specific container and don't care about the underlying hierarchy.
The result is beautifully achieved using this extension method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
public static class ControlCollectionExtensionMethods
{
public static IEnumerable<Control> FlattenedList(this ControlCollection controls)
{
foreach (Control ctrl in controls)
{
// return parent control
yield return ctrl;
// and dive into child collection
foreach (Control child in ctrl.Controls.FlattenedList())
yield return child;
}
}
}
P.S.: don't forget about namespaces when using it in your code, if above class is wrapped into namespace, for example: Sample, the source code file with calling code must explicitly reference it: using Sample;
© ASP.net Weblogs or respective owner