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));

Published by

Unknown's avatar

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

Leave a comment