How to add event handler to local variable in VB.NET

event-handling, local-variables, vb.net

Solution

It's recommended, for consistency, that you use the same source and event args model as all system event handlers.

Create your own class inheriting from EventArgs, as:

Public Class MyObjectEventArgs
    Inherits EventArgs

    Public Property EventObject As MyObject

End Class

Then declare your event, and a handler method, like:

Public Event ObjectCreated As EventHandler(Of MyObjectEventArgs)

Private Sub Container_ObjectCreated(ByVal sender As Object, ByVal e As MyObjectEventArgs)
    ' Handler code here
End Sub

Then attach the handler to your event using:

AddHandler ObjectCreated, AddressOf Container_ObjectCreated

Additionally, you can use the `Handles` to attach to the event raised from your main form (assuming the name MainForm), as below:

Private Sub MainForm_ObjectCreated(ByVal sender As Object, ByVal e As MyObjectEventArgs) Handles MainForm.ObjectCreated
    ' Handler code here
End Sub

Problem

I have a form in VB.NET that is used as a dialog in a mainform. Its instances are always locally defined, there's no field for it. When the user clicks the OK button in the dialog, it will fire an event with exactly one argument, an instance of one of my classes. Since it is always a local variable, how can I add an event handler for that event? I've searched for myself and found something but I can't really figure it out... Code for the event, a field in `MyDialog`: ``` public Event ObjectCreated(ByRef newMyObject as MyObject) ``` Code for the main form to call dialog : (never mind the syntax) ``` Dim dialog As New MyDialog() dialog.ShowDialog(Me) AddHandler ObjectCreated, (what do I put here?) //Or how do I add a handler? ``` As you can see I'm stuck on how to add a handler for my event. Can anyone help me? Preferrably with the best way to do it...

Original source