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

后端 未结 9 1026
别跟我提以往
别跟我提以往 2020-12-15 16:54

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 contr

相关标签:
9条回答
  • 2020-12-15 16:58

    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");
    
    0 讨论(0)
  • 2020-12-15 17:05

    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.

    0 讨论(0)
  • 2020-12-15 17:06

    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.

    0 讨论(0)
  • 2020-12-15 17:07

    Create a delegate in the user control and then assign it a method from the parent page.

    class MyUserControl : UserControl
    {
       delegate object MyDelegate(object arg1, object arg2, object argN);
       public MyDelegate MyPageMethod;
    
       public void InvokeDelegate(object arg1, object arg2, object argN)
       {
         if(MyDelegate != null)
            MyDelegate(arg1, arg2, argN); //Or you can leave it without the check 
                                          //so it can throw an exception at you.
       }
    }
    
    class MyPageUsingControl : Page
    {
       protected void Page_Load(object sender, EventArgs e)
       {
         if(!Page.IsPostBack)
            MyUserContorlInstance.MyPageMethod = PageMethod;
       }
    
       public object PageMethod(object arg1, object arg2, object argN)
       {
         //The actions I want
       }
    }
    
    0 讨论(0)
  • 2020-12-15 17:08

    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);
    }
    
    0 讨论(0)
  • 2020-12-15 17:10
    this.Page
    

    or from just about anywhere:

    Page page = HttpContext.Current.Handler as Page
    
    0 讨论(0)
提交回复
热议问题