add handlers to controls on runtime

ramone

Freshman
Joined
Sep 29, 2005
Messages
26
hello
i have a loop that creates controls with info from db, this controls are pictureboxes, after being created and configured they are added to a panel control, how can i set event handlers for click and double click events to this controls as they are created??

here is my code:

Visual Basic:
Private Sub fotos_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim dt As DataTable = selectDatos(Me.cnxStr, "select id_foto,ext from fotos where id_paciente=" + idpacientecur)
        Dim dr As DataRow
        Dim foto As PictureBox

'loop to create pictureboxes
        For Each dr In dt.Rows
            foto = New PictureBox
            foto.Size = New Size(90, 90)
            foto.SizeMode = PictureBoxSizeMode.StretchImage
            foto.Image = Image.FromFile(Me.path + "fotos\" + Me.idpacientecur + "\" + cString(dr.Item(0)) + "." + dr.Item(1))
'add to panel control
            panelFotos.Controls.Add(foto)
            foto.Location = New Point(Me.refx, Me.refy)
            foto.Cursor = Cursors.Hand
            Me.refx = Me.refx + 100
'here i want to add the event handlers for click and double click events
        Next
    End Sub

thanks for your help
 
Last edited:
You'll need to create a couple of event handlers for the click and double click events.


Visual Basic:
Private Sub Foto_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    'blah
End Sub

Private Sub Foto_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs)
    'blah
End Sub

Private Sub fotos_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim dt As DataTable = selectDatos(Me.cnxStr, "select id_foto,ext from fotos where id_paciente=" + idpacientecur)
        Dim dr As DataRow
        Dim foto As PictureBox

'loop to create pictureboxes
        For Each dr In dt.Rows
            foto = New PictureBox
            foto.Size = New Size(90, 90)
            foto.SizeMode = PictureBoxSizeMode.StretchImage
            foto.Image = Image.FromFile(Me.path + "fotos" + Me.idpacientecur + "" + cString(dr.Item(0)) + "." + dr.Item(1))
'add to panel control
            panelFotos.Controls.Add(foto)
            foto.Location = New Point(Me.refx, Me.refy)
            foto.Cursor = Cursors.Hand
            Me.refx = Me.refx + 100
            AddHandler foto.Click, AddressOf Foto_Click
            AddHandler foto.DoubleClick, AddressOf Foto_DoubleClick
        Next
End Sub

I hope that gives you and idea how to do it.
 
Back
Top