Flattening System.Web.UI ControlCollection
- by evovision
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;