Reputation: 39
I am trying to create a simple game, and first it needs to randomly load 16 PictureBoxes with images. I am not sure where the problem lies in this.
Public Class Form1
Private picArrows() As PictureBox = {pic11, pic12, pic13, pic14,
pic21, pic22, pic23, pic24,
pic31, pic32, pic33, pic34,
pic41, pic42, pic43, pic44}
Private Sub btnNew_Click(sender As Object, e As EventArgs) Handles btnNew.Click
'starts a new game
'declares RNG
Dim randGen As New Random
'uses RNG to determine arrow placement
For intPicBox As Integer = 0 To 15
Select Case randGen.Next(1, 5)
Case 1
picArrows(intPicBox).Image = My.Resources.Up
Case 2
picArrows(intPicBox).Image = My.Resources.Right
Case 3
picArrows(intPicBox).Image = My.Resources.Down
Case 4
picArrows(intPicBox).Image = My.Resources.Left
End Select
Next
End Sub
End Class
I get a NullReferenceException error on the line after Case X. Anyone know what I'm doing wrong?
Upvotes: 1
Views: 47
Reputation: 38865
I get a NullReferenceException error on the line after Case X
You cannot initialize your array like this:
Public Class Form1
Private picArrows() As PictureBox = {pic11, pic12, pic13, pic14,
pic21, pic22, pic23, pic24,
pic31, pic32, pic33, pic34,
pic41, pic42, pic43, pic44}
The Form has not been initialized yet, so it and all the controls on it have not been created yet. As a result, all those control references are going to be Nothing
, leaving you with an array full of Nothing
s. The result is a NullReferenceException
because Nothing
does not have an Image
property.
You can declare the array there, but you can only initialize it after the form's constructor runs (Sub New
). Form Load is a good place:
Public Class Form1
Private picArrows As PictureBox()
' for best results you should use the same RNG over and over too:
Private randGen As New Random()
...
Private Sub Form_Load(....
picArrows = New PictureBox() {pic11, pic12, pic13, pic14,
pic21, pic22, pic23, pic24,
pic31, pic32, pic33, pic34,
pic41, pic42, pic43, pic44}
See also NullReference Exception in Visual Basic
Upvotes: 1
Reputation: 754
Slightly different arrangement without the companion array:
Private Sub btnNew_Click(sender As Object, e As EventArgs) Handles btnNew.Click
With New Random
For col = 1 To 4
For row = 1 To 4
CType(Controls(String.Format("pic{0}{1}", col, row)), PictureBox).Image = {My.Resources.Up, My.Resources.Right, My.Resources.Down, My.Resources.Left}(.Next(0, 4))
Next
Next
End With
End Sub
Upvotes: 0