[英]Using linq to get list of web controls of certain type in a web page
有沒有辦法使用linq獲取網頁中的文本框列表,無論它們在樹層次結構或容器中的位置如何。 因此,不是循環遍歷每個容器的ControlCollection來查找文本框,而是在linq中執行相同的操作,可能在單個linq語句中?
我見過的一種技術是在ControlCollection上創建一個返回IEnumerable的擴展方法......如下所示:
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;
}
}
}
}
這處理遞歸。 然后你就可以在你的頁面上使用它,如下所示:
var textboxes = this.Controls.FindAll().OfType<TextBox>();
這將為您提供頁面上的所有文本框。 您可以更進一步,構建一個處理類型過濾的擴展方法的通用版本。 它可能看起來像這樣:
public static IEnumerable<T> FindAll<T>(this ControlCollection collection) where T: Control
{
return collection.FindAll().OfType<T>();
}
你可以像這樣使用它:
var textboxes = this.Controls.FindAll<TextBox>().Where(t=>t.Visible);
如果您的頁面有母版頁,並且您知道內容占位符名稱,則非常簡單。 我做類似的事情,但使用網絡面板
private void SetPanelVis(string PanelName)
{
Control topcontent = Form.FindControl("MainContent");
foreach (Control item in topcontent.Controls.OfType<Panel>())
{
item.Visible = (item.ID == RadioButtonList1.SelectedValue);
}
}
http://www.dotnetperls.com/query-windows-forms提供了我在這個問題上找到的最佳答案。 我選擇了LINQ版本:
/// <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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.