ZachJ ZachJ - 2 months ago 9
Vb.net Question

How can I use arrays for multiple buttons

I have 25 buttons, and when I click the button, It will disable itself and give you points. However, I am not really sure how to use an array to prevent repeating the same block of code for all 25 buttons. I tried this but I get errors in the output.

Line 4: Expression expected
Line 6: End of statement expected
Line 9: Expression does not produce a value.

Public Class SBCL

Dim number = New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25}
Dim score = As Integer

Private Sub Button(number)_Click(sender As Object, e As EventArgs) Handles Button14.Click
score = score + 1
MsgBox(score & " " & "points out of 25")
Button(number).Enabled = False
ProgressBar1.Value = ProgressBar1.Value + 4
End Sub

Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
MsgBox("Created by Nathen35 of Moonboy Development.")
End Sub

Private Sub ChangeLogToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ChangeLogToolStripMenuItem.Click
MsgBox("Version 0.4a: Exit button added. Progress bar added.")
End Sub

Private Sub Button18_Click(sender As Object, e As EventArgs) Handles Button18.Click
Close()
End Sub

End Class

Answer

change this part:

Public Class SBCL

    Dim score As Integer

    Private Sub Button_Click(sender As Object, e As EventArgs)
        Dim button = TryCast(sender, Button)
        If button Is Nothing Then Exit Sub

        score = score + 1
        MsgBox(score & " points out of 25")
        button.Enabled = False
        ProgressBar1.Value = ProgressBar1.Value + 4
    End Sub

Then in the Form designer select all 25 buttons > right-click them > Properties > Events > and in the Click event drop-down select the Button_Click:

enter image description here