Q:

Need to pass object through dynamically created event handler

Need to pass object through dynamically created event handler in vb.net application, (newperson is a usercontrol). The event handler:
AddHandler newperson.MouseUp, AddressOf newperson_MouseUp

Then I use this handler as follows,
Private Sub newperson_MouseUp()

End sub

But I need to refer to the newperson within this sub, e.g.
newperson.Background = Brushes.Black

Any input or ideas will be appreciated :).

A:

You need three things:

A custom EventArgs class where you store a reference to your newPerson object
Public Class MyMouseUpEventArgs
    Inherits MouseEventArgs

Public Sub New(newPerson As Person, b As MouseButtons, clicks As Integer, x As Integer, y As Integer, Delta As Integer)
    MyBase.New(b, clicks, x, y, Delta)
    Me.newPerson = newPerson
End Sub

Public Property newPerson As Person
End Class

It inherits from MouseEventArgs to also have the default event args, but this is not a must have.
In your custom control you need to handle the original MouseUp event. In this handler you simply raise a new custom event which I called MyMouseUp. This custom event takes as parameter the previously created MyMouseEventArgs with the new person
Public Class Person
       Inherits UserControl

Public Shared Event MyMouseUp(sender As Object, e As MyMouseUpEventArgs)

Public Sub New()
    AddHandler Me.MouseUp, AddressOf OnMouseUp
End Sub

Private Overloads Sub OnMouseUp(sender As Object, e As MouseEventArgs)
    RaiseEvent MyMouseUp(sender, New MyMouseUpEventArgs(Me, e.Button, e.Clicks, e.X, e.Y, e.Delta))
End Sub
End Class

The custom event must be shared so it can be used in the handler class without object reference shown in step
The handler (here just the main form) now registers to the new custom event with the custom event args. Thus you can access newPerson.
Public Class Form1

Public Sub New()
    InitializeComponent()

    AddHandler Person.MyMouseUp, AddressOf OnyMyMouseUp
End Sub

Private Overloads Sub OnyMyMouseUp(sender As Object, e As MyMouseUpEventArgs)
    'Do stuff
    e.newPerson.BackColor = Color.Aqua
End Sub
End Class

Hope that helps. The code is not tested so no warranty is given ;)

