views:

664

answers:

1

I have a flowLayoutPanel which I am programatically adding new panelLayouts to. Each panelLayout has a pictureBox within it. It's all working nicely, but I need to detect when that picture box is clicked on. How do I add an event to the picture? I seem to only be able to find c# examples....

my code to add the image is as follows...

        ' add pic to the little panel container
        Dim pic As New PictureBox()
        pic.Size = New Size(cover_width, cover_height)
        pic.Location = New Point(10, 0)
        pic.Image = Image.FromFile("c:/test.jpg")
        panel.Controls.Add(pic)

        'add pic and other labels (hidden in this example) to the big panel flow
        albumFlow.Controls.Add(panel)

So I assume somewhere when I'm creating the image I add an onclick event. I need to get the index for it also if that is possible! Thanks for any help!

+1  A: 

Use the AddHandler statement to subscribe to the Click event:

    AddHandler pic.Click, AddressOf pic_Click

The sender argument of the pic_Click() method gives you a reference to the picture box back:

Private Sub pic_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim pic As PictureBox = DirectCast(sender, PictureBox)
    ' etc...
End Sub

If you need additional info about the specific control, like an index, then you can use the Tag property.

Hans Passant
Thank you once again Hans, spot on!! I used the pic.tag and it's all perfect. :)
Matt Facer
Don't forget to remove the event handlers if/when you dispose of the form, otherwise they will hang around and eat up your resources.
camainc
It isn't necessary here. He adds the control to the Controls collection and the event handler is in the form. It gets thus disposed and the delegate reference cannot keep the form instance alive.
Hans Passant