Adding an event handler to a dynamically populated control

E

Elmo Watson

I've got a subroutine that can do something when the image in the Picturebox
is doubleclicked, that works just fine
Private Sub pb1_DoubleClick(ByVal sender As Object, ByVal e As
System.EventArgs) Handles pb1.DoubleClick
ShowImage(pb1)
End Sub

Private Sub ShowImage(ByVal ctrl As Control)
Dim PicForm As New MyForm
Dim img As Image
img = Image.FromFile(ctrl.Tag)
PicForm.LoadFile(img)
PicForm.ShowDialog()
End Sub

Now - Let's say I'm adding a picturebox to a panel, dynamically, and I set
the image dynamically (small image) - but I want to add an event handler, so
that when the small image in the new dynamically created Picturebox is
doubleclicked, it will call that function
Dim picBox as PictureBox= new PictureBox
' How can I change the above code to handle this new dynamically created
control - and then how can I add an event handler to do the same thing for
the new dynamically created control (when double-clicked)?

(I hope this is understandable)
 
B

Bryan Phillips

Add this method to your code:

Private Sub AddDynamicPictureBox()
Dim pb As New PictureBox()
Me.Controls.Add(pb)
AddHandler pb.DoubleClick, AddressOf pb1_DoubleClick

' Put code to load image into pb here.
End Sub
 
E

Elmo Watson

I guess I need to explain a little more
me.controls.add(pb) works just fine - it gets a thumbnail of a particular
image and loads it into the Picturebox.
I also add the original file path to the tag for each pb that gets loaded.
I want to add a double click event for each one, so that when it gets double
clicked, it opens another form I have (let's call it frmNew Pic, and load it
with the path from the tag of the individual picturebox that gets clicked.

I've got another scenario working, when clicking on a particular
Picturebox -
Sub pb1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs)
Handles pb1.DoubleClick
ShowImage(pb1)
End Sub

I'm trying to find a way to add a doubleclick event (no problem, really,
until I need it to have a control name passed to it)

My problem is that, with a signature like:
ByVal sender As Object, ByVal e As System.EventArgs
for a button's click event, I can't pass it a ctrl

See my dilemma?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top