在我的项目中,所有 .aspx 页面都继承自自定义基类页面,该页面又继承自 System.Web.UI.Page。我想在当前页面中找到控件。对于那个我正在使用 foreach 循环
foreach(control c in page.controls)
为此,我无法将当前页面转换为 system.web.ui.page。如何将当前页面投射到系统system.web.ui.page?
在我的项目中,所有 .aspx 页面都继承自自定义基类页面,该页面又继承自 System.Web.UI.Page。我想在当前页面中找到控件。对于那个我正在使用 foreach 循环
foreach(control c in page.controls)
为此,我无法将当前页面转换为 system.web.ui.page。如何将当前页面投射到系统system.web.ui.page?
你可以试试这个;
foreach(控制 c 在((System.Web.UI.Page)this.Page).Controls)
Please note that you are dealing with a control-tree, so you might want to have a recursion here. Following method should help (Linq with a recursive call):
private static IEnumerable<Control> FlattenControlTree<TFilterType>(Control control)
{
if (control is TFilterType)
{
yield return control;
}
foreach (Control contr in control.Controls.Cast<Control>().SelectMany((c) => FlattenControlTree<TFilterType>(c)))
{
if (contr is TFilterType)
{
yield return contr;
}
}
}
By the end of the day, you only need to call:
var controls = FlattenControlTree<YourBaseType>(this.Page);
Please note that this kind of recursion is not very effective when it comes to big trees.