-4

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

 cmdButton(0)
 cmdButton(1)
 cmdButoon(2)
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143

1 Answers1

1

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 
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
  • thanx men.. but this is my code in vb and i wanted to convert it to vb.net...i.e. i want three buttons to access the same code when i click them – Ajakaiye Taiwo Peter Jul 16 '12 at 07:15
  • thanx men.. but this is my code in vb and i wanted to convert it to vb.net...i.e. i want three buttons to access the same code when i click them: – Ajakaiye Taiwo Peter Jul 16 '12 at 07:15
  • thanx men.. but this is my code in vb and i wanted to convert it to vb.net...i.e. i want three buttons to access the same code on them same form when i click them: Private Sub cmdButton_Click(Index As Integer) ...... oQuestions(CLng(lblQuestion.Tag)).UserAnswer = iAnswer Ret = GetQuestion(Index) ' Index is 0 or 1 - (cmdButton_Click(0) or cmdButton_Click(1)) .... cmdButton(1).Enabled = True End If cmdButton(0).Enabled = True cmdButton(2).Visible = False Else ..... – Ajakaiye Taiwo Peter Jul 16 '12 at 07:23
  • Well - that is what you should have posted in your original question then. Start a new question with this code explaining what you want to ultimately achieve. – Matt Wilko Jul 16 '12 at 08:01