简体   繁体   English

如何在VB.NET中为以编程方式创建的对象创建事件处理程序?

[英]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": 例如,假设我创建一个名为“ 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? 如何为MyButton实现事件处理程序?

You use AddHandler and AddressOf like this: 您可以这样使用AddHandlerAddressOf

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

There is more info here in the MSDN documentation: MSDN文档中有更多信息:

With the newer versions of VB.NET you can use a lambda expression inline instead of an entire method (if you want) 使用VB.NET的较新版本,可以内联使用lambda表达式,而不是使用整个方法(如果需要)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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