Tuesday, March 1, 2011

Calling Parent Page method from Child Usercontrol using Reflection in ASP.Net

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
Here txtMessege.Text Represent any of the existing control
So you can see how easily we can call a method in the parent page using the user control placed on that page.

No comments:

Post a Comment