Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

asp.net - Using linq to get list of web controls of certain type in a web page

Is there a way to use linq to get a list of textboxes in a web page regardless of their position in the tree hierarchy or containers. So instead of looping through the ControlCollection of each container to find the textboxes, do the same thing in linq, maybe in a single linq statement?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One technique I've seen is to create an extension method on ControlCollection that returns an IEnumerable ... something like this:

public static IEnumerable<Control> FindAll(this ControlCollection collection)
{
    foreach (Control item in collection)
    {
        yield return item;

        if (item.HasControls())
        {
            foreach (var subItem in item.Controls.FindAll())
            {
                yield return subItem;
            }
        }
    }
}

That handles the recursion. Then you could use it on your page like this:

var textboxes = this.Controls.FindAll().OfType<TextBox>();

which would give you all the textboxes on the page. You could go a step further and build a generic version of your extension method that handles the type filtering. It might look like this:

public static IEnumerable<T> FindAll<T>(this ControlCollection collection) where T: Control
{
    return collection.FindAll().OfType<T>();
}

and you could use it like this:

var textboxes = this.Controls.FindAll<TextBox>().Where(t=>t.Visible);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...