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?
CodePudding user response:
Move the array initialisation into Sub Main()
Visual components are not initialised at the point that form level variables are initialised.
CodePudding user response:
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.