Calling a method in parent page from user control

Here is the classic example using events as suggested by Freddy Rios (C# from a web application project). This assumes that you want to use an existing delegate rather than make your own and you aren't passing anything specific to the parent page by event args.

In the user control's code-behind (adapt as necessary if not using code-behind or C#):

public partial class MyUserControl : System.Web.UI.UserControl
{
    public event EventHandler UserControlButtonClicked;

    private void OnUserControlButtonClick()
    {
        if (UserControlButtonClicked != null)
        {
            UserControlButtonClicked(this, EventArgs.Empty);
        }
    }

    protected void TheButton_Click(object sender, EventArgs e)
    {
        // .... do stuff then fire off the event
        OnUserControlButtonClick();
    }

    // .... other code for the user control beyond this point
}

In the page itself you subscribe to the event with something like this:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // hook up event handler for exposed user control event
        MyUserControl.UserControlButtonClicked += new  
                    EventHandler(MyUserControl_UserControlButtonClicked);
    }
    private void MyUserControl_UserControlButtonClicked(object sender, EventArgs e)
    {
        // ... do something when event is fired
    }

}

Cast the page as the specific page in your project:

((MyPageName)this.Page).CustomMethod()

I suggest you don't call the page method directly, as you would be tying your control to the specific page.

Instead expose an event, and have the page subscribe to it. It works for any number of pages, can more easily be used when the control is multiple times on a single page (perhaps even on a list) and is more in line with asp.control design.


Follow good and appropriate approach,

Use event and delegate concept make delegate as same signature as your method in parent page and then assign parent methad to it in parent page load event then call this delegate through event in user control.

code sample and link is given below.

//Parent Page aspx.cs part

 public partial class getproductdetails : System.Web.UI.Page
 {
  protected void Page_Load(object sender, EventArgs e)
  {
   ucPrompt.checkIfExist += new uc_prompt.customHandler(MyParentMethod);
  }

  bool MyParentMethod(object sender)
  {
   //Do Work
  }
}

//User control parts
public partial class uc_prompt : System.Web.UI.UserControl
{
 protected void Page_Load(object sender, EventArgs e)
 {
 }

 public delegate bool customHandler(object sender);
 public event customHandler checkIfExist;
 protected void btnYes_Click(object sender, EventArgs e)
 {
  checkIfExist(sender);
 }
}

Read more details how it works (Reference) :-

Calling a method of parent page from user control