C# Custom Events in ASP.net Web Controls

First create an EventArgs class for your event. This is the class that will be passed through your event and holds values of interest to controls watching for the events fired by your custom control.

public class TemplateDisplayCommandEventArgs
{
#region Public Properties

public int SelectedTemplateId { get; private set; }

#endregion

#region Initializers

public TemplateDisplayCommandEventArgs(int templateId)
{
SelectedTemplateId = templateId;
}

#endregion
}

Then create the event handling delegate which will handle the passing of the EventArgs class through the event.

public delegate void TemplateDisplayCommandEventHandler(object sender, TemplateDisplayCommandEventArgs e);

Now within the code of your custom control add a public event of the EventHandler delegate type.

public event TemplateDisplayCommandEventHandler TemplateSelected;

Create a virtual method which will handle the calling of the event based on actions within the custom control.

protected virtual void OnTemplateSelected(TemplateDisplayCommandEventArgs e)
{
if (TemplateSelected != null) TemplateSelected(this, e);
}

Now from within your code you can simply call the virtual method when ever you want to fire the event.

OnTemplateSelected(new TemplateDisplayCommandEventArgs(Template.Id));

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s