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
    .Where(tb => tb.Text.Trim().Length == 0)

// and focus it
if (firstEmpty != null)

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


Comments have been disabled for this content.