Event Handling for Dynamic Objects

Bocky

Member
Joined
Nov 7, 2008
Messages
5
Programming Experience
1-3
I am trying to create a form where depending on what the user selects, they are shown a collection of images from the web. Depending on what they select there will be a different amount of images so each picture will need to be added dynamically.

I am able to create PictureBoxes dynamically however I'm stumped how to create event handling in order for each control to give a unique response.

This is what I originally tried but I got an error..

VB.NET:
Private Sub Form1_Load

For i=0 To 10

 Dim picBox As PictureBox
 picBox = New PictureBox
 picBox.Name = "Picture" & x.ToString()
 AddHandler picBox.Click, AddressOf ClickHandler(picBox.Name)
 Controls.Add(picBox)

Next i+


End Sub

Private Sub ClickHandler(ByVal picname As String)

  If picname = "Picture1" Then
 
   MsgBox("This is the first picturebox - VB.NET is so logical!")

  End If

End Sub

The error I got was
'AddressOf' operand must be the name of a method (without parentheses)

How ridiculous that you can't include arguments in your AddressOf! Can anyone shed some light on my situation (or knows a better way of carrying out my goal)?

Help is much appreciated :)
 
That right. You must provide an event signature for the click event
VB.NET:
Private Sub PB_Click([COLOR="Red"]ByVal sender As Object, ByVal e As EventArgs[/COLOR]) ' <- this is the event signature, now you can code away
  label1.Text = DirectCast(sender, Picturebox).Name
End Sub
This is how you dynamically add an event handler for it, which is similar to how you do it in the designer when you double click a control it make the default event for you. You don't need the Handles clause because you have the pointer with the Addhandler statement.
 
Back
Top