Dynamic controls with one event.

Squirm

Centurion
Joined
May 21, 2001
Messages
139
Location
London, England
I'm creating a number of pictureboxes dynamically:

Visual Basic:
For i = 0 To 14
    pPicture = New PictureBox()
    cPics.Add(pPicture, CStr(i))
    Me.Controls.Add(pPicture)

    pPicture.Width = 60
    pPicture.Height = 60
    pPicture.Left = (iPositions(i) Mod 4) * 60
    pPicture.Top = (iPositions(i) \ 4) * 60
    pPicture.Visible = True

    pPicture.Image = Image.FromFile("C:\EVBFpuzzle\" & CStr(i) & ".bmp")
Next i

All is well, the pictureboxes appear as they should. Now comes the part I'm having difficulty with. I want to have a procedure which handles the click event for all of these pictureboxes. Just one procedure.

How would I go about achieving this?
 
Use AddHandler to bind the event to a procedure in every loop iteration:

Visual Basic:
AddHandler pPicture.Click, AddressOf myProcedure

Private Sub myProcedure(sender As Object, e As System.EventArgs)
'sender is the picturebox that raised the event
End Sub
 
Back
Top