How to Call a Method in ASPX Page(CodeBehind) from a UserControl in C# and ASP.Net ?
Sometimes, we will have a scenario where we need to call 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. Refer below,
WebUserControl.ascx <%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %> <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
WebUserControl.ascx.cs public partial class WebUserControl : System.Web.UI.UserControl { public event EventHandler usrCtrlSaveClick;
protected void Page_Load(object sender, EventArgs e) {
} protected void btnSave_Click(object sender, EventArgs e) { //do some operations usrCtrlSaveClick.Invoke(this, new EventArgs()); } }
PageUC.aspx.cs public partial class PageUC : 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.usrCtrlSaveClick += new EventHandler(this.usrctrlSaveClick); } public void PageMethodinCodeBehind() { //refresh or do some required operations Response.Write("Hello from Page codebehind!"); } protected void usrctrlSaveClick(object sender, EventArgs e) { PageMethodinCodeBehind(); } }
In the above code, the event usrctrlSaveClick(object sender, EventArgs e) in codebehind file will be invoked from btnSave click in the user control. You can call your page method from the page event. I have called PageMethodinCodeBehind() method from the usrctrlSaveClick() event. You can use this method to refresh any control or to do some operations on the page whenever you click save in user control.
|