LINQ - The Uber FindControl

With a simple extension method to ControlCollection to flatten the control tree you can use LINQ to query the control tree:

public static class PageExtensions
{
    public static IEnumerable<Control> All(this ControlCollection controls)
    {
        foreach (Control control in controls)
        {
            foreach (Control grandChild in control.Controls.All())
                yield return grandChild;

            yield return control;
        }
    }
}
Now I can do things like this:
// get the first empty textbox
TextBox firstEmpty = accountDetails.Controls
    .All()
    .OfType<TextBox>()
    .Where(tb => tb.Text.Trim().Length == 0)
    .FirstOrDefault();

// and focus it
if (firstEmpty != null)
    firstEmpty.Focus();

Pretty cool! I can do all sorts of querying of the control tree now. LINQ you are my hero.

19 Comments

Comments have been disabled for this content.