在vb.net中为动态按钮创建多个单击事件

时间:2016-11-15 19:05:55

标签: vb.net

创建按钮时,我想为每个按钮创建一个点击事件。如何为动态创建的每个按钮创建单击事件?这是我的代码。它可以根据创建的第一个按钮创建单个事件。

    Sub CreateDynamicButton()
    Dim ButtonNumber As Integer = 1
    Dim axisX As Integer = 53
    Dim axisY As Integer = 13
    ' Create a Button object 
    Do Until ButtonNumber = 11
        Dim dynamicButton As New Button
        ' Set Button properties
        dynamicButton.Location = New Point(axisX, axisY)
        dynamicButton.Height = 30
        dynamicButton.Width = 200
        ' Set background and foreground
        dynamicButton.BackColor = Color.Beige
        dynamicButton.ForeColor = Color.Black
        dynamicButton.Text = "I am Dynamic Button" & ButtonNumber
        dynamicButton.Name = "DynamicButton" & ButtonNumber
        dynamicButton.Font = New Font("Georgia", 10)
        AddHandler dynamicButton.Click, AddressOf dynamicButton_Click
        ' Add Button to the Form. Placement of the Button
        ' will be based on the Location and Size of button
        Controls.Add(dynamicButton)
        axisY = axisY + 35
        ButtonNumber = ButtonNumber + 1
    Loop
    'Add Exit Button
    Dim dynamicButtonExit As New Button
    ' Set Button properties
    dynamicButtonExit.Location = New Point(axisX, axisY)
    dynamicButtonExit.Height = 30
    dynamicButtonExit.Width = 200
    ' Set background and foreground
    dynamicButtonExit.BackColor = Color.Beige
    dynamicButtonExit.ForeColor = Color.Black
    dynamicButtonExit.Text = "Exit"
    dynamicButtonExit.Name = "Exit"
    dynamicButtonExit.Font = New Font("Georgia", 10)
    AddHandler dynamicButtonExit.Click, AddressOf dynamicButtonExit_Click
    ' Add Button to the Form. Placement of the Button
    ' will be based on the Location and Size of button
    Controls.Add(dynamicButtonExit)
End Sub

2 个答案:

答案 0 :(得分:0)

您无需创建多个事件来处理动态按钮,dynamicButton_Click足以处理所有点击。更好地为每个按钮提供ID,您只需在此事件中执行,执行以下代码:

Dim btn As Button = DirectCast(sender, Button)
If btn.ID = "DynamicButton1" then
    'Do logic here for button 1
End If

答案 1 :(得分:0)

您只需添加一点逻辑来处理一个事件处理程序中的每个按钮单击。如果您使用' Select Case'声明它保持整洁。

如果每个按钮的逻辑都有很多代码,那么为每个按钮编写单独的子代码并使用每个' Case'来调用相应的子代码可能会更好。像第二个案例块一样阻止

Private Sub DynamicButton_click(sender As Object, e As EventArgs)
    Dim btn As Button = DirectCast(sender, Button)
    Select Case btn.Name
        Case "DynamicButton1"
            MessageBox.Show("button1")
        Case "DynamicButton2"
            dynamicbutton2_Click(sender, e)
    End Select
End Sub

Private Sub dynamicbutton2_Click(sender As Button, e As EventArgs)
    MessageBox.Show("Button2")
    'and lots of other code
End Sub