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

前端 未结 2 464
太阳男子
太阳男子 2020-11-28 13:44

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 = \"MyButt         


        
相关标签:
2条回答
  • 2020-11-28 14:02

    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
    
    0 讨论(0)
  • 2020-11-28 14:13

    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
    0 讨论(0)
提交回复
热议问题