简体   繁体   中英

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?

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM