The event model in Visual Basic allows reacting to user actions through event handlers that are linked to controls. This is critical for GUI (Graphical User Interface) applications, where each element can trigger its own events.
In classic VB6, event handling was implemented through static binding of control to method. In VB.NET and WinForms, the model became more flexible: now multiple handlers can be attached to a single event, supporting dynamic binding through AddHandler/RemoveHandler.
A typical issue is the dynamic addition of controls and management of their events. If you do not unsubscribe from events or incorrectly link a handler, memory leaks, duplicate calls, and loss of control over UI behavior may occur.
When creating controls dynamically, use AddHandler for subscribing and RemoveHandler for correctly removing the handler. Pay attention to the lifespan of controls — if a control is destroyed, it is necessary to unsubscribe handlers; otherwise, "dangling" references will remain.
Example code:
Dim btn As New Button() AddHandler btn.Click, AddressOf ButtonClickHandler ' ... RemoveHandler btn.Click, AddressOf ButtonClickHandler Sub ButtonClickHandler(sender As Object, e As EventArgs) MessageBox.Show("Button clicked!") End Sub
Key features:
What happens if the event handler is connected multiple times to the same element?
The handler will be called as many times as it was added via AddHandler, which may lead to unexpected multiple executions of logic.
AddHandler btn.Click, AddressOf Handler AddHandler btn.Click, AddressOf Handler ' When the button is clicked, Handler will be called 2 times
Can a method with parameters that differ from the event signature be used?
No, the handler method signature must strictly match the event delegate (for example, Sub Handler(sender As Object, e As EventArgs)). The compiler will throw an error otherwise.
Does RemoveHandler remove all occurrences of the handler if it has been added multiple times?
No, RemoveHandler removes only one subscription per call. If the handler was added multiple times, it needs to be removed that many times; otherwise, one instance will remain linked.
100 buttons are dynamically created in a loop, and an event handler is assigned to all, but RemoveHandler is not called. After closing the form, the event continues to "live", which leads to frequent crashes.
Pros:
Cons:
An event handler is added to each dynamic control in the collection, and when a control is removed, all handlers are explicitly unsubscribed in a loop.
Pros:
Cons: