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?
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);
If your page has a master page and you know the content placeholder name, it is pretty easy. I do something similar but with web panels
private void SetPanelVis(string PanelName)
{
Control topcontent = Form.FindControl("MainContent");
foreach (Control item in topcontent.Controls.OfType<Panel>())
{
item.Visible = (item.ID == RadioButtonList1.SelectedValue);
}
}
You're going to need recursion to iterate through all children of all controls. Unless there's some reason you have to implement this with LINQ (I assume you mean lambdas), you might try this approach using Generics instead.
http://www.dotnetperls.com/query-windows-forms provides the best set of answers I've found to this question. I chose the LINQ version:
/// <summary>
/// Use a LINQ query to find the first focused text box on a windows form.
/// </summary>
public TextBox TextBoxFocusedFirst1()
{
var res = from box in this.Controls.OfType<TextBox>()
where box.Focused == true
select box;
return res.First();
}
精彩评论