Search code examples
c#asp.netuser-controlsparent

Call page method after usercontrol events ends


Hey, How can i call a page method after a usercontol finished his method / fire a parent page method from inside the user control insted?


Solution

  • The most elegant solution would be to have your UserControl raise an event which is handled by the parent page.

    In your user control, define an event and raise it:

    public partial class WebUserControl1 : System.Web.UI.UserControl {
        public event EventHandler MyMethodIsFinished;
    
        // ...
    
        protected void MyMethod {
            // ...
            if (MyMethodIsFinished != null)
                MyMethodIsFinished(this, EventArgs.Empty);
        }
    }
    

    In your page, embed the user control and define a handler:

    <uc1:WebUserControl1 ID="MyWebUserControl1" runat="server"
                         OnMyMethodIsFinished="MyMethodIsFinishedHandler" />
    

    Then write the handler code in the page:

    protected void MyMethodIsFinishedHandler(object sender, EventArgs e) {
        // do something
    }
    

    If you need to pass data to your event handler, the recommended way is to subclass EventArgs, as shown in this example.