Monday, January 3, 2011

How to Call a Method on container ASPX Page from a UserControl in C# and ASP.Net ?

Invoking a Page Method from User control in C#



Scenario:

Calling a method defined in the page CodeBehind file from a user control.

For example, if you want to refresh some controls in page when you saved some data in user control through an event in the user control.



To do this, we can define an event handler in the CodeBehind and it can be invoked from user control whenever required. From the event in the page we can call the page method which can refresh the page controls.



This sample code explains how to create event handler for page events and invoking the event in User Control



WebUserControl.ascx



<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>



<asp:Button ID="btnSave" runat="server" Text="btnSave" OnClick="btnSave_Click" />





WebUserControl.ascx.cs



public partial class WebUserControl : System.Web.UI.UserControl

{

public event EventHandler ehClick;



protected void Page_Load(object sender, EventArgs e)

{



}



protected void btnSave_Click(object sender, EventArgs e)

{

ehClick.Invoke(this, new EventArgs());

}

}





Default.aspx.cs



public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

//Register an event handler which will be invoked from the user control

this.WebUserControl1.ehClick += new EventHandler(this.btnPageButton_Click);

}



public void SaveData()

{

//Page Method

/*



Code



*/

//Displaying Current Date

Response.Write(System.DateTime.Now.ToString());



}



protected void btnPageButton_Click(object sender, EventArgs e)

{

SaveData();

}

}