Brendan Enrick

Daily Software Development

Fun With Web Forms Controls and LINQ

Since LINQ has come out I’ve been very fascinated with it. LINQ to SQL is kind of cool, but working with in-memory collections is my favorite. Sure anything we can do with LINQ we could have done before, but now it’s easy. While not exactly the most practical and certainly not the most efficient method of handling things, working with a page’s Controls collection can be a lot of fun.

So perhaps I want to change the text of all of the TextBoxes on a page. I can easily grab that collection like this.

IEnumerable<TextBox> textBoxes = Page.Controls.
    Where(c => c.GetType() == typeof(TextBox)).Select(t => (TextBox)t);

Well sort of except that some controls will not be in that collection because this is a tree structure so I’ll make a recursive method which will get me all of the controls on the page.

public IEnumerable<Control> AllControls(Control root)
{
    if (root != null)
    {
        if (root.Controls.Count < 1)
        {
            yield return root;
        }
        foreach (Control c in root.Controls)
        {
            if (c.Controls.Count < 1)
            {
                yield return c;
            }
            else
            {
                foreach (var control in AllControls(c))
                {
                    yield return control;
                }
            }
        }
    }
}

Now we can work with a page having nested controls. Fun eh? Here is how you can get all of those controls and set the Text property of TextBox ones to their own IDs.

IEnumerable<TextBox> boxes = AllControls(Page).
    Where(c => c.GetType() == typeof(TextBox)).Select(t => ((TextBox)t));
foreach (var textBox in boxes)
{
    textBox.Text = textBox.ID;
}

Try it out with a page with textboxes in a login view. It works. Enjoy. Have fun!

Loading