vb.net 如何在 Visual Basic 2010 中为运行时创建的控件创建单击事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14948332/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:23:29  来源:igfitidea点击:

How to make a click event for runtime created controls in Visual Basic 2010?

vb.net

提问by Steve Butcher

I added some controls to my form at runtime and I need them to call a function when clicked. I don't know how many controls will be added but they all need to run the same function. How would I define the event? Can I define events based on all controls of a given class?

我在运行时向表单添加了一些控件,我需要它们在单击时调用函数。我不知道将添加多少控件,但它们都需要运行相同的功能。我将如何定义事件?我可以根据给定类的所有控件定义事件吗?

回答by Parimal Raj

A simple example :

一个简单的例子:

Public Class Form1


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' creating control
        Dim btn1 As Button = New Button()
        Dim btn2 As Button = New Button()

        btn1.Parent = Me
        btn1.Name = "btn1"
        btn1.Top = 10
        btn1.Text = "Btn1"

        btn2.Parent = Me
        btn2.Name = "btn2"
        btn2.Top = 50
        btn2.Text = "Btn2"

        'adding handler for click event
        AddHandler btn1.Click, AddressOf HandleDynamicButtonClick
        AddHandler btn2.Click, AddressOf HandleDynamicButtonClick


    End Sub

    Private Sub HandleDynamicButtonClick(ByVal sender As Object, ByVal e As EventArgs)
        Dim btn As Button = DirectCast(sender, Button)

        If btn.Name = "btn1" Then
            MessageBox.Show("Btn1 clicked")
        ElseIf btn.Name = "btn2" Then
            MessageBox.Show("Btn2 Clicked")
        End If

    End Sub
End Class

回答by SysDragon

Simply:

简单地:

AddHandler Control.Event, AddressOf MethodExecuting

For example:

例如:

AddHandler Button1.Click, AddressOf ClickMethod