After promising you a post on using delegates to create events several times, I’m now using my break to post it. Because it will be a while if I wait until I can find the time… 😉
As I mentioned earlier a delegate can be seen as an interface for a method. Because you don’t know what the method that will handle an event on your user control will look like, delegates are a great way to provide your user control with events. (For the basics on delegates see my post on them earlier).
First, you will have to declare the delegate that will be used to call the event. This is no different from the regular delegate declaration.
//Define public delegate
public delegate void OnLabelTextChanged(object sender, EventArgs e);
Next, you will have to declare a local variable to hold the method that handles your event. This way you can check if the eventhandler was implemented by the calling application. If it was, you can trigger the event. If it wasn’t, don’t 😉
private OnLabelTextChanged ltcDelegate;
The last step is to add the event to the available events for the user control. You do this by declaring a public virtual event of the type you named your delegate. The text between the brackets places this event in the category “property changed” with the description “Text was changed”.
//Declare public event of delegate type
[Category(“Property changed”), Description(“Text was changed”)]
public virtual event OnLabelTextChanged LabelTextChanged
//point event to local delegate variable
ltcDelegate += value;
ltcDelegate -= value;
This way, the local variable (ltcDelegate in this example) will be null if the eventhandler was not implemented. If the eventhandler was implemented, you can call the eventhandler. In this example the eventhandler is triggered when the text for a label changes. This is the code in the property for the text:
public string LabelText
_lbltxt = value;
lblDelTest.Text = _lbltxt;
//if eventhandler is implemented, trigger it
if (ltcDelegate != null)
That’s how easy it is to use delegates to create an event for your user control! If you have any questions: contact me through the contact page, or drop a line in the comments.