In Visual Basic (VB.NET), dynamic creation of controls is done by creating an instance of the desired class and adding it to the Controls collection. To handle events for dynamically created controls in VB.NET, delegates and the AddHandler statement are used:
Example (VB.NET):
Dim btn As New Button() btn.Text = "Click me!" btn.Location = New Point(40, 40) Me.Controls.Add(btn) AddHandler btn.Click, AddressOf Button_Click Private Sub Button_Click(sender As Object, e As EventArgs) MessageBox.Show("Dynamically created button clicked.") End Sub
In classic VB6, dynamic creation and event handling for controls are only possible through control arrays, where the indices distinguish separate elements:
Example (VB6):
' A CommandButton with Index = 0 must be on the form Load Command1(1) Command1(1).Visible = True Private Sub Command1_Click(Index As Integer) MsgBox "Button with index " & Index & " pressed!" End Sub
It should be noted that in VB.NET there is no concept of control arrays as in VB6 — event handling for dynamically created controls is ensured only by the delegate mechanism and AddHandler/RemoveHandler.
Question: "What happens if you forget to call RemoveHandler for events of a dynamically created control before its destruction? What consequences can this have?"
Answer: If you forget to call RemoveHandler before removing the control, the reference to the handler will remain in memory, leading to a memory leak, and sometimes to an attempt to access an already destroyed object or form, which will throw an exception.
Example:
' Forgotten RemoveHandler: ' AddHandler btn.Click, AddressOf SomeHandler ' Controls.Remove(btn) ' btn is no longer there, but the handler remains
Story
In a billing system for payment terminals, dynamic buttons were created on the panel for payment operations. After the window was closed, the remaining event handlers interfered with garbage collection. Over a week, the application caused memory leaks, leading to server crashes and the need to manually restart the process during nightly operations.
Story
In a medical visualization project on WinForms, a large number of "image previews" were created and destroyed using PictureBoxes. The developer didn't remove event handlers. After 20-30 loads, the application began to lag: it turned out that thousands of hidden handlers continued to hang, blocking resource release.
Story
In one of the educational applications for children, quiz buttons were dynamically formed and removed from the form after the game, but events were not unsubscribed via RemoveHandler. Because of this, upon starting a new game, there were "ghostly" triggers of checker code, leading to outdated popups, score-keeping bugs, and general confusion.