Calling a method in parent page from user control
Asked Answered
B

10

43

I've a user control registered in an aspx page On click event of a button in the user control, how do i call a method which is there in the parent page's codebehind?

Thanks.

Bathelda answered 8/3, 2009 at 5:52 Comment(0)
H
126

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
    }

}
Harem answered 8/3, 2009 at 10:7 Comment(8)
Stephen, a helpful and concise answer. +1.Alverson
i wish i could give you +2 :)Hiatt
What if I would like to RETURN something to the usercontrol, with a non void MyUserControl_UserControlButtonClicked?Dawn
The perfect way +1 for this... :)Stier
I don't think this is 100% correct. I think in Page_Load() MyUserControl.UserControlButtonClicked +=new EventHandler(MyUserControl_UserControlButtonClicked); should be replaced with ControlName.UserControlButtonClicked +=new EventHandler(MyUserControl_UserControlButtonClicked); - that is name for specific control should be used instead of the class name.Arms
The example is correct as a guide, but yes adapt to use the IDs as you defined them in the hosting page's aspx.Harem
'Public Event UserControlButtonClicked(sender As Object, e As System.EventArgs)' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event.Phonolite
how to send value with event ?Montagnard
P
15

Cast the page as the specific page in your project:

((MyPageName)this.Page).CustomMethod()
Polacre answered 8/3, 2009 at 5:54 Comment(2)
@Henk of course it breaks best practices, but If the asker doesn't understand something simple like how this works, how will s/he be able to understand bigger things later. Always best to use the simplest way first, even if its wrong, just to learn.Polacre
I agree Rex, this is what the asker asked about and it is nice to answer the question, rather than always tell that the question was wrong.Adherent
P
10

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.

Palace answered 8/3, 2009 at 6:34 Comment(0)
T
6

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

Toluene answered 29/5, 2013 at 11:36 Comment(0)
A
4

Scott Allen has a useful article on event bubbling from a user control to the parent page, which elaborates on the answer provided by Stephen M. Redd:

Alverson answered 13/8, 2009 at 9:36 Comment(0)
D
2

I want to do this scenario:

  • Call LoadEditCategory method (parent method).
  • Parent method (LoadEditCategory) needs a int argument (CategoryID).
  • Child user control is RightControlPanel that is in same parent page folder.

Child User control

1- Add a Action (_LoadEditCategory)

public Action<int> _LoadEditCategory = null;

<int> is int argument (CategoryID).

2- Use this Action in button event (btnSavebutton name) like this:

void btnSave_Click(object sender, EventArgs e)
{
    //123 is test integer for CategoryID
    _LoadEditCategory(123);        
}

Parent Page or parent user control

3- Add parent method

 private void LoadEditCategory(int CategoryID)
    {
     // CategoryID is 123 in my example
     //Do some things with CategoryID
    }

4- Add this code when load child user control (RightControlPanel)

//Load child user control
RightControlPanel si = this.LoadControl(this.ControlPath + "RightControlPanel.ascx") as RightControlPanel;
if (si != null) 
 {
   ...

   //For call parent method in child user control
   si._LoadEditCategory = c => LoadEditCategory(c);

   ...
 }
Drainpipe answered 14/12, 2016 at 8:50 Comment(0)
S
0
 //c#
 //In parent page
 public void test(string S)
 {
    Label1.Text = S;
  }

 //In user control
 protected void Button1_Click(object sender, System.EventArgs e)
 {
 //Calling "test method" of parent page  from user control  
 ((object)this.Page).test("Hello!!");
 }

 'VB.Net 
'In parent page
 Sub test(ByVal S As String)
    Label1.Text = S
 End Sub

 'In user control
  Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
  'Calling "test method" of parent page  from user control  
  DirectCast(Me.Page, Object).test("Hello!!")
  End Sub 
Shrug answered 10/11, 2014 at 14:53 Comment(0)
B
0

I love Stephen M. Redd's answer and had to convert it to VB. Sharing it here. Suggested edits welcome.

In the user control's code-behind:

Public Class MyUserControl
    Inherits System.Web.UI.UserControl

    'expose the event publicly
    Public Event UserControlButtonClicked As EventHandler 

    'a method to raise the publicly exposed event
    Private Sub OnUserControlButtonClick()

        RaiseEvent UserControlButtonClicked(Me, EventArgs.Empty)

    End Sub

    Protected Sub lbtnApplyChanges_Click(sender As Object, e As EventArgs) Handles lbtnApplyChanges.Click

        'add code to run here, then extend this code by firing off this event
        'so it will trigger the public event handler from the parent page, 
        'and the parent page can hanlde it

        OnUserControlButtonClick()

    End Sub

End Class

In the parent page subscribe to the event, so when the event is raised, your code will run here.

Public Class SalesRecord
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        'hook up event handler for exposed user control event to handle this
        AddHandler MyUserControl.UserControlButtonClicked, AddressOf MyUserControl_UserControlButtonClicked

    End Sub

    ''' <summary>
    ''' code to run when user clicks 'lbtnApplyChanges' on the user control
    ''' </summary>

    Private Sub MyUserControl_UserControlButtonClicked()

        'this code will now fire when lbtnApplyChanges_Click executes

    End Sub

End Class
Blubbery answered 15/2, 2018 at 18:30 Comment(0)
S
0

I posted something that works here: Access control > page > master nested > master

Or if you want access to a control you can also do this:

Update parent page Where parent has an update panel named "UpdatePanel1"

Control

UpdatePanel onParent1 = (UpdatePanel)Parent.FindControl("UpdatePanel1");
onParent1.Update();
Santiago answered 7/3, 2019 at 23:45 Comment(0)
O
-7

You can use Session . Say when you click on a button in user control and when you want to call Parent page method then in event handler of button click set value as

Session["CallParent"]="someValue";

as button will post back the page . On Page_Load event of Parent Page add it

protected void Page_Load(object sender,EventArgs e)
{
   if(Session["CallParent"]!=null)
   {
      // here call the Parent Page method 
      Method1();
      // now make the session value null
     Session["CallParent"]=null;
    }
}

It is much more efficient

Overleap answered 18/2, 2011 at 6:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.