Vigan Ajvazi Vigan Ajvazi - 1 year ago 81 Question

How would I handle a click event for a Programmatically created for a button?

I would like to click a button I have created programmatically, and for it to generate a message box (Visual Basic)
This is the code that generates the button:

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)

Answer Source

Simply add an EventHandler

AddHandler theButton.Click, AddressOf Me.theButton_Click

Then in your handling method you need to compare the sender with your button object. If they match, you can work with this button.

Public Class Form1
    Private WithEvents NodeButton As Button

    Public Sub New()

        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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download