.Net Hive

A blog about Microsoft .Net Platform & other industry happenings

Custom Events in ASP.NET User Controls

Hello Everyone,

Yesterday I was working on a user control and I came across a situation where I wanted to notify the parent page when ever the button in the user control get clicks.

This situation calls for a requirement of having a custom event associated with the user control I can then use in the host page, which encapsulates the user control.

Here is the core source code to required to achieve this functionality:

CustomUserControl.ascx.cs

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

public partial class CustomUserControl : System.Web.UI.UserControl
{
public event EventHandler SubmitClick;

protected void btnSubmit_Click(object sender, EventArgs e)
{
this.OnSubmitClick(e);
}

protected void OnSubmitClick(EventArgs e)
{
if (SubmitClick != null)
{
SubmitClick(this, e);
}
}
}

Because I needed the event to be executed when ever the submit button get executed, there for I invoked the method at the Submit button click. You can change it according to your requirement.

HostWebPage.aspx.cs

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

public partial class HostWebPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
userCustomControl.SubmitClick += new EventHandler(userCustomControl_SubmitClick);
}

void userCustomControl_SubmitClick(object sender, EventArgs e)
{
//DO ANY WORK
}
}

I tried to make this example as simple as possible. Let me know if this helped. Any suggestion or queries are welcome.

Happy Reading

Waqas Ahmed

Advertisements

Filed under: ASP.NET, , , ,

Pages

Categories

Archives

.Net Hive @ Twitter

Blog Directory by Blog Flux
Computers/Tech blogs