👨‍🚀💬

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

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
}

~ posted in professional on 06.08.2011