Calling Parent Page method from Child Usercontrol using Reflection in ASP.Net
 
Author:
Filed Under: ASP.Net  |  C#.Net  |  VB.Net  |  Snippets
Published Date: Apr 12, 2010
Views: 10821
 

Abstract: Here Mudassar Ahmed Khan has explained how to call parent page method from child user control placed on the same page whose function or method we want to call.

Comments:  17

 

Here I am explaining how to call parent page method or function from child user control i.e. a user control added to the same page whose function or method we want to call.
 
Parent Page Method
It is very important that the parent page method is declared as public otherwise the child user control will not be able to call the method. Below is the method that I want to call. This function simply accepts a string variable message and displays it on the screen
C#
public void DisplayMessage(string message)
{
   Response.Write(message);
}
 
VB.Net
Public Sub DisplayMessage(ByVal message As String)
        Response.Write(message)
End Sub
 
Child User Control Method
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.
C#
protected void btnSend_Click(object sender, EventArgs e)
{
    this.Page.GetType().InvokeMember("DisplayMessage", System.Reflection.BindingFlags.InvokeMethod, null, this.Page, new object[] { txtMessage.Text });
}
 
VB.Net
Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As EventArgs)
        Me.Page.GetType.InvokeMember("DisplayMessage", System.Reflection.BindingFlags.InvokeMethod, Nothing, Me.Page, New Object() {txtMessage.Text})
End Sub
 
So you can see how easily we can call a method in the parent page using the user control placed on that page.
Attached is the sample code in VB.Net and C#
CallingParentPageMethodFromChildUserControl.zip
 








Related Articles



Comments



Add comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
Please do not post code, scripts or snippets.

Name*: Required
Email*: Required
Comment*: Required
Security code*: CaptchaInvalid Security Code
  Submit