CSharpFeeds - All your C# feeds in one place.

Sponsors

Wednesday, September 23, 2009

Fun With Web Forms Controls and LINQ

by Brendan Enrick via Brendan Enrick on 9/23/2009 2:00:00 PM

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!

email it!bookmark it!digg it!

Original Post: Fun With Web Forms Controls and LINQ

Subscribe

New Feed

Product Spotlight

Recently Updated Sources

Legal Note

The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us