2

在我的项目中,所有 .aspx 页面都继承自自定义基类页面,该页面又继承自 System.Web.UI.Page。我想在当前页面中找到控件。对于那个我正在使用 foreach 循环

foreach(control c in page.controls)

为此,我无法将当前页面转换为 system.web.ui.page。如何将当前页面投射到系统system.web.ui.page?

4

2 回答 2

0

你可以试试这个;

foreach(控制 c 在((System.Web.UI.Page)this.Page).Controls)

于 2013-09-06T15:50:15.560 回答
0

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.

于 2013-09-06T15:10:10.387 回答