24

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?

2 Answers 2

38

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:

Sign up to request clarification or add additional context in comments.

Comments

19

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.