2016-10-20 11 views
-1

我想按我已編程方式創建一個按鈕,併爲它生成一個消息框(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() 
+3

的[動態按鈕單擊事件處理程序(http://stackoverflow.com/questions/7375061/dynamic-button-click-event-handler) –

+1

也有可能重複[這](HTTP://計算器.com/questions/7291461/how-do-i-create-an-event-handler-for-a-programmatically-created-object-in-vb-net)and [this](http://stackoverflow.com/問題/ 21642678/how-can-i-create-dynamic-button-click-event-on-dynamic-button-vb-net)和[this](http://stackoverflow.com/questions/14948332/how-to -make-a-click-event-for-runtime-created-controls-in-visual-basic-2010) –

+0

谷歌你的標題和答案可能會在那裏爲你。 – Bugs

回答

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 
相關問題