How do I create an event handler for a programmatically created object in VB.NET?

Say I have an object that I dynamically create. For example, say I create a button called "MyButton":

Dim MyButton as New Button()
MyButton.Name = "MyButton"

How do I create, say, a "Click" event? If it were statically created I could create a function as:

Private Sub MyButton_Click(ByVal sender as system.object, ByVal e As System.EventArgs) Handles.

How do I implement an event handler for MyButton?


Solution 1:

You use AddHandler and AddressOf like this:

Dim MyButton as New Button()
MyButton.Name = "MyButton"
AddHandler MyButton.Click, AddressOf MyButton_Click

There is more info here in the MSDN documentation:

  • How to: Add an Event Handler Using Code

Solution 2:

With the newer versions of VB.NET you can use a lambda expression inline instead of an entire method (if you want)

Dim MyButton as New Button()
MyButton.Name = "MyButton"
AddHandler MyButton.Click, Sub(sender2, eventargs2)
                               'code to do stuff
                               'more code to do stuff
                           End Sub