使用linq获取网页中某种类型的网页控件列表
问题描述:
有没有一种方法可以使用linq来获取网页中的文本框列表,而不管它们在树层次结构或容器中的位置。因此,不是循环遍历每个容器的ControlCollection来查找文本框,而是在linq中执行相同的操作,也许只需要一个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);
答
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();
}
答
如果你的页面有一个母版页,你知道的内容占位符的名称,这是很容易的。我做了类似的事情,但使用网络面板
private void SetPanelVis(string PanelName)
{
Control topcontent = Form.FindControl("MainContent");
foreach (Control item in topcontent.Controls.OfType<Panel>())
{
item.Visible = (item.ID == RadioButtonList1.SelectedValue);
}
}
此解决方案不会递归搜索控制树。搜索很浅。 – 2012-08-08 16:52:18