问题
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?
回答1:
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);
回答2:
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.
回答3:
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();
}
回答4:
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);
}
}
来源:https://stackoverflow.com/questions/3613561/using-linq-to-get-list-of-web-controls-of-certain-type-in-a-web-page