I remember that when I first started moving from VB6 to VB.NET, I really missed the comfort zone of the relatively easy to use control array in Classic VB. But I soldiered on and got to grips with all that business of creating a new control, setting properties, adding it to the Form’s Controls array and creating an event handler.
I think that learning to use AddHandler was probably the biggest leap from Classic-Think to
.NET-Speak.** You know the sort of code I’m talking about:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim PB As New PictureBox
With PB
.Image = Image.FromFile("h:\oscar.bmp")
.Location = New System.Drawing.Point(50, 50)
.Size = New Size(90, 90)
End With
' Add to the Controls collection
Me.Controls.Add(PB)
' Wire this control up to an appropriate event handler
AddHandler PB.Click, AddressOf MyPicClicked
End Sub
' The aforementioned Event Handler:
Private Sub MyPicClicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
' Code in here to react to the Click event
MessageBox.Show("You clicked the new PictureBox")
End Sub
Just leafing through one of my books the other night, I discovered by chance that all that AddHandler angst was probably wasted aggravation. Simply declaring your planned new control(s) using the WithEvents keyword anywhere in the Code Window outside a procedure will give you access to the whole range of Events for that type of control by default.
Something like:
Dim WithEvents PBWE As PictureBox
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
PBWE = New PictureBox
With PBWE
.Name = "PBWE1"
.Location = New Point(200, 50)
.Size = New Size(70, 70)
.Image = Image.FromFile("h:\oscar.bmp")
End With
Controls.Add(PBWE)
End Sub
And with that code in place, you can go into the code window, select “PBWE” from the left hand side ComboBox and all the available Events will appear for your selection as normal in the right hand box.
So, taking the Click event as a random example, you code this event just as if the control already existed at Design Time (although it won’t actually exist until that button is clicked at Run Time, of course) .
Private Sub PBWE_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles PBWE.Click
MessageBox.Show("You Clicked on PBWE")
End Sub
This “revelation” has probably been documented hundreds of times around the place but for some strange reason I have never come across it before.
Not entirely sure how useful it will be to you, but having made the discovery I thought I'd blog it.
** The irony is that as I sit here now and type this I realise that using AddHandler seems the most natural thing in the world. But back at Day Zero of the two year Classic-to-Net learning curve it all seemed very complicated indeed!