Closer Look: Handling Events

In the previous lesson, you learned how to add an event to the Persons class and raise the event so that other code can respond to it. In this lesson, you will learn how to associate an event with an event handler that you will create.

If you want to write code that will respond to an event (or handle the event), you must associate the event with an event handler. You can do this by using either the Handles or Add Handler statement. The Add Handler statement enables you to associate events to event handlers at run time, whereas the Handles statement associates events to event handlers only at compile time. The Handles statement can be added to the end of any subroutine that has the same signature as the event. For example, in the previous lesson, you added an event named AgeCalculated that takes an integer parameter. The subroutine that you create to handle the event must also take an integer parameter, as the following code illustrates.


Private Sub person1_AgeCalculated(
    ByVal Age As Integer) Handles person1.AgeCalculated


The object person1 must be created by using the WithEvents statement so that the AgeCalculated event can be accessed.

When you use the Add Handler statement, you can associate events with event handlers dynamically at run time. You can learn about how to use the Add Handler statement in Events and Event Handlers.

In this lesson, you learned how to associate an event with an event handler at design time. In the next lesson, you will learn how to test the event handler that you created by using a test project.

Next Lesson: Testing a Class

Show: