Alex Rivera | Logout

How can I get the parent page from a User Control in an ASP.NET Website (not Web Application)

Asked 2009-06-22T19:19:00.643
34

Just as the subject asks.

EDIT 1

Maybe it's possible sometime while the request is being processed to store a reference to the parent page in the user control?

Edit
Report

4 Answers

64
this.Page

or from just about anywhere:

Page page = HttpContext.Current.Handler as Page
answered 2009-06-22T19:21:51.247
14

I cannot think of any good reason for a user control to know anything about the page it is on as the user control should be ignorant of its context and behave predictably regardless of what page it is on.

That being said, you can use this.Page.

answered 2009-06-22T19:23:54.080
2

I always used this.Page in the System.Web.UI.UserControl.

Or you can always do a recursive call on the Parent until u encounter an object that is a Page.

kind of overkill though...

protected Page GetParentPage( Control control )
{
    if (this.Parent is Page)
        return (Page)this.Parent;

    return GetParentPage(this.Parent);
}
answered 2009-06-22T19:28:14.150
1

You must use NamingContainer like that:

       try
        {
            if (!string.IsNullOrWhiteSpace(TargetCtrlID))
            {
                var ctrl = NamingContainer.FindControl(TargetCtrlID);
                if(ctrl != null)
                    Console.Write("'" + ctrl.ClientID + "'");
            }
        }
        catch
        {

        }
answered 2012-04-09T16:38:13.287

Your Answer