VB.NET 中动态添加按钮并添加点击事件

Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click 
    Dim btn(10) As Button 
    Dim count1 As Int16 
    For count1 = 0 To 10 
        btn(count1) = New Button 
        btn(count1).SetBounds(400, 5 + count1 * 45, 150, 40) 
        btn(count1).Text = "我是第" & count1 + 1 & "个按钮" 
        btn(count1).Tag = count1 
        Me.Controls.Add(btn(count1)) 
        AddHandler btn(count1).Click, AddressOf Me.btClick 
    Next 

End Sub 
Private Sub btClick(ByVal sender As Object, ByVal e As EventArgs) 
    Dim btn As Button 
    btn = CType(sender, Button) 
    MsgBox(btn.Tag.ToString.PadLeft(3, "0") & ":" & btn.Text) 
End Sub 

本代码通过点击button15来创建11个按钮并添加到界面中。
注意的是创建按钮的索引是利用按钮的tag属性保存的。
创建后按钮的click方法被转到btclick函数上去了
AddHandler btn(count1).Click, AddressOf Me.btClick

另外mark下批量写click事件:

 Private Sub FormEqui_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim ct As Control
    '遍历 checkbox
    For Each ct In Me.GroupBox1.Controls
        If (TypeOf ct Is CheckBox) Then
            Dim ch As System.Windows.Forms.CheckBox = DirectCast(ct, System.Windows.Forms.CheckBox)
            For i As Integer = 1 To 30 Step 1

                If (ch.Name = "CheckBox" & i) Then
                    '批量写入事件
                    AddHandler ch.Click, AddressOf Me.btClick

                End If
            Next
        End If
    Next

End Sub

Private Sub btClick(ByVal sender As Object, ByVal e As EventArgs)
    MessageBox.Show("click")
End Sub

你可能感兴趣的:(VB.NET 中动态添加按钮并添加点击事件)