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

85,436

Solution 1

this.Page

or from just about anywhere:

Page page = HttpContext.Current.Handler as Page

Solution 2

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.

Solution 3

you can use the Parent property

if you need this to find a control on the page then you can use

Label lbl_Test = (Label)Parent.FindControl("lbl_Test");

Solution 4

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);
}

Solution 5

I found the way to do this is to create an interface, implement that interface, use this.Page to get the page from the control, cast it to the interface, then call the method.

Share:
85,436
JoeB
Author by

JoeB

Updated on January 29, 2020

Comments

  • JoeB
    JoeB over 4 years

    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?

  • jtate
    jtate about 10 years
    this is a great point. well defined user controls should be completely independent of the page they're on.
  • cavillac
    cavillac over 9 years
    If the application in question is a silo'ed application and all pages inherit from a BasePage class and you need to access that BasePage then this.Page is a completely acceptable solution as all pages in that application will inherit from that BasePage and the Control will be defined solely for that application.
  • humbads
    humbads over 7 years
    A good use case for this is to access the Page.Items collection, which can be used to store objects that are used for the lifetime of the Asp.net page processing cycle. You can avoid reloading common objects in every user control.
  • MC9000
    MC9000 about 5 years
    That is great in an ideal world, but there are many cases where parts of a control may have a condition requirement dependent on the calling page. A good example is if a control is used on every page and that control displays or logs it's calling page (for whatever reason, like internal tracking, debugging, even security reasons).
  • Allen
    Allen over 3 years
    Except if the uc is in another uc on a tab on a page..... etc. etc. ??