Dirt Simple C# .NET Custom Event for UserControl
Here’s my simple version
using System.ComponentModel; //Define a class to hold the event arguments, if one isn't already defined. public class DesignEventArgs : EventArgs { private DesignListItem item; public DesignEventArgs(DesignListItem item) { this.item = item; } public DesignListItem Item { get { return this.item; } } } //Create a delegate handler outside the user control class public delegate void SelectionChangedEventHandler(object sender, DesignEventArgs e); public partial class MySimpleUserControl : UserControl { //Declare the event using the delegate handler. Set a Browsable so it shows in the designer [Browsable(true)] public event SelectionChangedEventHandler SelectionChangedEvent; //Method that raises the event protected virtual void OnSelectionChangedEvent(DesignEventArgs e) { //Ensure the event is not null SelectionChangedEventHandler sceh = this.SelectionChangedEvent; if (sceh !=null) sceh(this, e); } //Finally, the method which raises the event public void DoStuffToRaiseEvent() { //data for event args DesignListItem listItem = new DesignListItem(); //build event args DesignEventArgs args = new DesignEventArgs(listItem); //Raise the event OnSelectionChangedEvent(args); } }
Now, over on the form… If your event is NOT displayed in the Designer’s Event List, you’ve done something wrong but this should register the event.
//In the form constructor add: myUserControl.DesignChangedEvent += new DesignChangedEventHandler(myUserControl_DesignChangedEvent); //And add this method: protected void myUserControl_DesignChangedEvent(object sender, DesignEventArgs e) { //Do your stuff }
Leave a Reply