Here is some example code that demonstrtes how to dynamically create buttons and assigne event handlers. In addition the created buttons are also copied into an array which gives you an alternate means of access a dynamically created button. Thie code uses the array to rename all the buttons if the form is clicked instead of a button. Clicking a button will change the button color to red or green.
Public Class Form1
Private m_btnArray(4, 4) As Button
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Me.Width = 65 * 7 '(width of 5 buttons + margins)
Me.Height = (35 * 7) + 35
createArray() 'add 5x5 array of buttons
End Sub
Private Sub createArray()
Dim newbtn As Button
Dim x, y, cnt, btnTop, btnLeft As Integer
btnTop = 0 'initalize
For y = 0 To 4
btnTop += 35
btnLeft = 0 'initalize
For x = 0 To 4
btnLeft += 65
newbtn = New Button
Me.Controls.Add(newbtn) 'add new button to form
AddHandler newbtn.Click, AddressOf multiButton_Click
With newbtn
.Name = "myBTN_" & cnt
.Width = 60
.Height = 30
.Text = "Btn_" & cnt
.Top = btnTop
.Left = btnLeft
.Visible = True
.Enabled = True
End With
m_btnArray(x, y) = newbtn
cnt += 1
Next
Next
End Sub
Private Sub multiButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Click
Dim btn As New Button
Dim x, y, cnt As Integer
Dim txt As String
Static Dim nameCnt As Integer
If btn.GetType Is sender.GetType Then
'sender is a button
btn = sender
If btn.BackColor = Color.Red Then
btn.BackColor = Color.LightGreen
Else
btn.BackColor = Color.Red
End If
Else
'assume the form has been clicked, change text of all buttons
For y = 0 To 4
For x = 0 To 4
txt = nameCnt & "Btn_" & cnt
m_btnArray(x, y).Text = txt
cnt += 1
Next
Next
nameCnt += 1
End If
End Sub
End Class