如何处理以编程方式为按钮创建的单击事件?

时间:2016-10-20 09:30:51

标签: vb.net visual-studio

我想单击我以编程方式创建的按钮,并为其生成一个消息框(Visual Basic) 这是生成按钮的代码:

Dim NodeButton As New Control
NodeButton.Name = "Button" & NodeID
NodeButton.BackColor = Color.Red
NodeButton.Text = NodeID
NodeButton.Size = New Point(ButtonSize, ButtonSize)
NodeButton.Location = New System.Drawing.Point(Xcoordinate, YCoordinate)
frmMain.Controls.Add(NodeButton)
NodeButton.BringToFront()

1 个答案:

答案 0 :(得分:1)

只需添加EventHandler

即可
AddHandler theButton.Click, AddressOf Me.theButton_Click

然后在您的处理方法中,您需要将sender与按钮对象进行比较。如果匹配,您可以使用此按钮。

Public Class Form1
    Private WithEvents NodeButton As Button

    Public Sub New()
        InitializeComponent()

        Me.NodeButton = New Button()
        ' Add it to UI
        AddHandler Me.NodeButton.Click, AddressOf Me.nodeButton_Click
    End Sub

    Private Sub nodeButton_Click(sender As Object, e As EventArgs)
        If (sender Is Me.NodeButton) Then
            'Do what you want
        End If
    End Sub
End Class