When you work with ASP.NET page, you might need to enumerate all controls of a specific type, i.e. text boxes, dropdown list, or table cells. All these controls derive from System.Web.UI.Control class.
To find all controls you need to iterate them recursively from the top one, i.e. Page, or any element that is located on a page (panel, table, etc.). One of the solution is to write an extension method like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public static IEnumerable<Control> GetAllControls(this Control parent) { foreach (Control control in parent.Controls) { yield return control; if (control.HasControls()) { foreach (Control child in control.GetAllControls()) { yield return child; } } } } |
Also you can use a generic version.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public static IEnumerable<T> GetAllControls<T>(this Control parent) where T : Control { foreach (Control control in parent.Controls) { if (control is T) { yield return (T)control; } if (control.HasControls()) { foreach (T child in control.GetAllControls<T>()) { yield return child; } } } } |
When I need to find all table cells with a specific ID, I can write the following LINQ query:
1 2 |
var cells = Table1.GetAllControls<TableCell>() .Where(c => c.ID != null && c.ID.StartsWith("Prefix")); |
In C# 6.0 and later you can use Elvis operator in Where clause.
1 2 |
var cells = Table1.GetAllControls<TableCell>() .Where(c => c.ID?.StartsWith("Prefix")); |