Thursday, October 7, 2010

Calling a method in the parent page upon clicking a button in a .NET user control

Lots of people probably know this already, but it was new to me.

Suppose you have a button (or other control) in an ASP.NET user control, and when the button is clicked, you'd like to call a method in the containing page, so that the page can take some appropriate action.

One way to do this is with InvokeMethod. You can even pass a value from the user control to the parent page.

A tip of the hat to Rajshree Mittal for this post that pointed the way.

My example consists of four files: Default.aspx, MyUserControl.ascx, Default.aspx.cs, and MyUserControl.ascx.cs. The two .CS files are provided here.

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "before";
}

public void DisplayMessage(string message)
{
Label1.Text = message;
}
}


MyUserControl.aspx.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MyUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{

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

No comments:

Post a Comment