Using Regex and Yield to Recursively Find Multiple Controls
This is a simple extension method that finds all child controls whose ID matches the regex pattern.
The Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Text.RegularExpressions; | |
using System.Web.UI; | |
public static class ControlHelpers | |
{ | |
public static IEnumerable<Control> FindControlsRecursive(this Control root, string regex) | |
{ | |
foreach (Control child in root.Controls) | |
{ | |
if (!string.IsNullOrWhiteSpace(child.ID)) | |
{ | |
if (Regex.Match(child.ID, regex).Success) | |
{ | |
yield return child; | |
} | |
} | |
if (child.Controls.Count > 0) | |
{ | |
foreach (Control c in FindControlsRecursive(child, regex)) | |
{ | |
yield return c; | |
} | |
} | |
} | |
} | |
} |
Demonstration
foreach (Control control in pnlExample.FindControlsRecursive(@"[^QuestionID]"))
{
// do something
}