Adding event handlers to object created programatically

davearia

Centurion
Joined
Jan 4, 2005
Messages
184
Hi,

I am creating an instance of a control within my form programatically like so:
Visual Basic:
Private Sub SetUp()
    For Each r As DataRow In dvFilter.ToTable.Rows
        Dim o As New ctlMachine(sPath, r)
    Next
End Sub
Within this control there is this event:
Visual Basic:
Private Sub PictureBox1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseClick
    RaiseEvent MouseClicked(dr)
End Sub
This in turn is handled by this event declaration in the same control:
Visual Basic:
Public Event MouseClicked(ByVal r As DataRow)

But I am struggling to reference this event at form level.

How do I wire this event up to the form?

Cheers, Dave.
 
There are two ways to wire events at runtime: WithEvents and AddHandler.

WithEvents looks neater in code and VB takes care of most of the work, but it requires a special pre-defined variable. It would be done like so:
Visual Basic:
Private WithEvents PictureBox SomePictureBox
 
Sub SomeEventHandler(sender As Object, e As EventArgs) Handles SomePictureBox.Click
    'Do some stuff
End Sub
 
Sub ExampleCode()
    'When we assign a picturebox to this variable the event is automatically wired.
    SomePictureBox = new PictureBox()
    'The event is automatically unwired when another picture box or Nothing is assigned to the variable

    Controls.Add(SomePictureBox)
End Sub

The AddHandler method can be much more dynamic and is more consistent with other languages, but takes more work and is less structured.
Visual Basic:
Sub SomeEventHandler(sender As Object, e As EventArgs)
    'Do some stuff
End Sub
 
Sub ExampleCode()
    Dim SomePictureBox As New PictureBox()
    Controls.Add(SomePictureBox)
 
    'We manually wire the event here.
    AddHandler SomePictureBox.Click, AddressOf SomeEventHandler
    'To unwire the event, we would use the RemoveHandler statement.
End Sub
You can use either method to wire any event to a handler declared in your form. In your case you probably want to go with AddHandler.
 
Back
Top