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




     //Declare local variable of delegate type
     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
         
add
         
{
              
ltcDelegate += value;
         
}
         
remove
         
{
              
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:



     [Category(“Appearance”), DefaultValue(“”)]
     public string LabelText
    
{
         
get
         
{
              
return _lbltxt;
         
}
         
set
         
{
              
_lbltxt = value;
              
lblDelTest.Text = _lbltxt;
              
//if eventhandler is implemented, trigger it
              
if (ltcDelegate != null)
              
{
                   
ltcDelegate(this, EventArgs.Empty);
              
}
         
}
    
}


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.