如何为 VB.NET 中以编程方式创建的对象创建事件处理程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7291461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I create an event handler for a programmatically created object in VB.NET?
提问by GregH
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 实现事件处理程序?
回答by Rick Sladkey
You use AddHandlerand AddressOflike this:
你使用AddHandler并AddressOf喜欢这个:
Dim MyButton as New Button()
MyButton.Name = "MyButton"
AddHandler MyButton.Click, AddressOf MyButton_Click
There is more info here in the MSDN documentation:
MSDN 文档中有更多信息:
回答by Thraka
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

