Home
VB.NET
WithEvents: Handles and RaiseEvent
Updated Apr 28, 2023
Dot Net Perls
WithEvents. This is a special syntax for events in VB.NET. We can add events with the Handles keyword. We do not need to ever call AddHandler or wire up events.
With the WithEvents keyword, we specify a class that contains an event. Then we can use Handles to handle the events in that class. This is powerful.
Consider this Module. We have a nested class EventClass that contains an Event called TestEvent. The Sub RaiseEvents also is present in EventClass.
Info EventClassInstance is a special variable on the Module. We create an instance of the EventClass.
Here We have 2 Subs that both use the Handles keyword. They handle the TestEvent that is present inside the EventClassInstance variable.
Module Module1 ' An instance of the Event class. WithEvents EventClassInstance As New EventClass Sub PrintTestMessage() Handles EventClassInstance.TestEvent ' This method handles the TestEvent. Console.WriteLine("Test Message Being Printed...") End Sub Sub PrintTestMessage2() Handles EventClassInstance.TestEvent ' This method also handles the event. Console.WriteLine("Test Message 2 Being Printed...") End Sub Sub Main() ' Call into the Event class and raise the test events. EventClassInstance.RaiseEvents() End Sub Class EventClass Public Event TestEvent() Sub RaiseEvents() ' Raise the Test event. ' ... This needs to be part of the class with the Event. RaiseEvent TestEvent() End Sub End Class End Module
Test Message Being Printed... Test Message 2 Being Printed...
Notes, an advantage. There is a clear advantage of WithEvents-style syntax in VB.NET. We can add new event handlers (like PrintTestMessage2) without calling AddHandler.
So There is less overhead for adding new event handlers. We just need to add the Sub itself.
A summary. We handled events with the Handles keyword in VB.NET. This syntax form has some advantages over AddHandler—we do not need to use a statement to add each new handler.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 28, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen