Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
 How to: Connect Event Handler Metho...

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Developer's Guide
How to: Connect Event Handler Methods to Events

To consume events defined in another class, you must define and register an event handler. The event handler must have the same method signature as the delegate declared for the event. You register your event handler by adding the handler to the event. After you have added your event handler to the event, the method is called whenever the class raises the event.

For a complete sample that illustrates raising and handling events, see How to: Raise and Consume Events.

To add an event handler method for an event

  1. Define an event handler method with the same signature as the event delegate.

    C#
    public class WakeMeUp 
    {
        // AlarmRang has the same signature as AlarmEventHandler.
        public void AlarmRang(object sender, AlarmEventArgs e)
        {...};
        ...
    }
    
    

    Visual Basic
    Public Class WakeMeUp
       ' AlarmRang has the same signature as AlarmEventHandler.
       Public Sub AlarmRang(sender As Object, e As AlarmEventArgs)
          ...
       End Sub
       ...
    End Class
    
  2. Create an instance of the delegate, using a reference to the event handler method. When the delegate instance is called, it in turn calls the event handler method.

    C#
    // Create an instance of WakeMeUp.
    WakeMeUp w = new WakeMeUp();
    
    // Instantiate the event delegate.
    AlarmEventHandler alhandler = new AlarmEventHandler(w.AlarmRang);
    
    

    Visual Basic
    ' Create an instance of WakeMeUp.
    Dim w As New WakeMeUp()
    
    ' Instantiate the event delegate.
    Dim alhandler As AlarmEventHandler = AddressOf w.AlarmRang
    
  3. Add the delegate instance to the event. When the event is raised, the delegate instance and its associated event handler method is called.

    C#
    // Instantiate the event source.
    AlarmClock clock = new AlarmClock();
    
    // Add the delegate instance to the event.
    clock.Alarm += alhandler;
    
    

    Visual Basic
    ' Instantiate the event source.
    Dim clock As New AlarmClock()
    
    ' Add the delegate to the event.
    AddHandler clock.Alarm, AddressOf w.AlarmRang
    
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker