Call UserControl method from Its parent page

17,298

Whatever you set the ID="" attribute to when you put the control on the page is the variable name you can use to reference it from within the page.

So if your page looks like this:

<my:UserControl runat="server" ID="myControl" />

Then you can just do:

myControl.MyControlMethod()

The method being invoked in the user control from the parent must be public. If it's private or protected, the method can't be called from the parent.

Also, instead of invoking page functions via reflection, you might be better off using events.

Share:
17,298
karthik k
Author by

karthik k

Updated on June 09, 2022

Comments

  • karthik k
    karthik k almost 2 years

    I got an approach like this to call an Parent Page method from its User Control.This "DisplayMessage" function simply accepts a string variable message and displays it on the screen. In the user control I have placed a textbox and a button. On the click event of the Button I am calling the Parent Page method we discussed above using Reflection and passing the value of the textbox to the method and then the method is invoked and the message is displayed on the screen.

    Parent Page:

    public void DisplayMessage(string message)
    {
       Response.Write(message);
    }
    

    User Control:

    protected void btnSend_Click(object sender, EventArgs e)
    {
        this.Page.GetType().InvokeMember("DisplayMessage",System.Reflection.BindingFlags.InvokeMethod, null, this.Page, new object[] { txtMessage.Text });
    }
    

    It works fine for me.

    Now what I need is, I have to call a method which exists in UserControl from its parent page.

    Please suggest me. Thanks in Advance.