Command button array

1.8k Views Asked by At

How can I create a array of buttons in VB.NET?

 cmdButton(0)
 cmdButton(1)
 cmdButoon(2)
1

There are 1 best solutions below

4
On

You can create an array like this

Dim btnCommand(2) As Button

But you will have to add it to your form and add a click handler in order for this to do a anything useful:

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim y As Integer = 25
    Dim btnCommand(2) As Button
    For i As Integer = 0 To btnCommand.Length - 1
        btnCommand(i) = New Button
        Me.Controls.Add(btnCommand(i))
        With btnCommand(i)
            .Top = y
            .Tag = i
            .Text = "Button " + i.ToString
        End With
        y += 25
        AddHandler btnCommand(i).Click, AddressOf ButtonArray_Click
    Next
End Sub

Private Sub ButtonArray_Click(sender As System.Object, e As System.EventArgs)
    Dim btn As Button = sender
    MsgBox("Button " + btn.Tag.ToString + " was clicked")
End Sub