VB.NET Dynamic Usage of EventHandlers
Category:Forms and Controls
Version Compatibility: Visual Basic.NET
In VB.NET we can receive and handle events in 2 ways. The first one is using WithEvents and Handles keywords. The second way is to use the AddHandler method and dynamically add event handlers through our code. We can also use RemoveHandler to dynamically remove them. WithEvents and Handles clause we have to declare the object variable and the event handler as we write our code so linkage is created upon compilation. On the other hand with AddHandler and RemoveHandler linkage is created and removed at runtime, which is more flexible. Let’s assume that we want to load several MDI child forms, allowing each of them to be loaded only once and of course to know when one of the child forms is closed. Since we have several forms to load we would like to use the AddHandler and RemoveHandler keywords so we can be flexible and write the minimal code we can.
Instructions: Copy the declarations and code below and paste directly into your VB project.