2

In my project all of the .aspx pages inherit from a custom base class page which in turn inherits from System.Web.UI.Page. I want to find the controls in current page. for that one I am using foreach loop

foreach(control c in page.controls)

for this I am unable to cast my current page to system.web.ui.page. how to cast the current page to system system.web.ui.page?

1
  • You can do like ((System.Web.UI.Page)this.Page).Controls. What is your issue? Have you face any error? Commented Sep 6, 2013 at 7:28

2 Answers 2

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.

0

You may try this;

foreach(Control c in ((System.Web.UI.Page)this.Page).Controls)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.