0

I'm trying to make a pair matching game, to learn visual basic, and I'm struggling with getting control arrays to work how I want them to.

Here's my code,

Public Class Form1
Dim buttonArray As Button() = {Button1, Button2, Button3, Button4, Button5, Button6,
    Button7, Button8, Button9, Button10, Button11, Button12, Button13, Button14,
    Button15, Button16}

    Sub main()

    End Sub

    Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click

        For button As Integer = 0 To 15
            buttonArray(button).Text = "test"
        Next


    End Sub
End Class

If I run it, I get 'Object reference not set to an instance of an object.' when I press the button. Moving the declaration of the array down into the private sub fixes it, and it works as intended, but that would mean I can't use the array in other private subs, only that one, correct?

How do I make the control array work correctly, and be availible to use in any sub I like?

Jimi
  • 29,621
  • 8
  • 43
  • 61
CharlRae
  • 1
  • 2
  • Think your problem is more in the loop than the array. Maybe do some reading on the _for each_ loop pattern which makes iterations of collections much simpler – Hursey Aug 13 '22 at 19:16
  • 1
    https://stackoverflow.com/a/72428361/14171304 – dr.null Aug 13 '22 at 21:23
  • Remove that `Sub main()` there. Use a standard Windows Forms template to build your Project (if you found that in some *example*, the example was about something else and someone decided to make a *shortcut*, creating a bad example in the process). – Jimi Aug 13 '22 at 23:37

2 Answers2

1

You can declare the array field at the class level but you cannot create the array and assign it to the field at that point because the controls haven't been created yet. As it is, your array is created before the form's constructor is executed. It's that constructor that calls the InitializeComponent method that creates the controls.

You can either create your own constructor and create the array after the InitializeComponent call or you can handle the Load event of the form and create in the event handler. I would recommend the latter, unless you specifically need to use the array before calling Show or ShowDialog on the form.

user18387401
  • 2,514
  • 1
  • 3
  • 8
0

Move the array initialisation into Sub Main()

Visual components are not initialised at the point that form level variables are initialised.

Steve Todd
  • 126
  • 5