0

http://pastebin.com/3A4P61Gt The code in question is specifically at line 143. Whenever I try to access a label in the array like so Dicelbls(0).Text I get a null reference error. Obviously I am not declaring the array right, any suggestions?

Ethan
  • 227
  • 3
  • 7

4 Answers4

1

You are right, the problem is at line 143:

Dim Dicelbls As Label() = {lblP1Die0, lblP1Die1, lblP1Die2, lblP2Die0, lblP2Die1, lblP2Die2, lblP1Score, lblP2Score}

Specifically, at the point in the object initialization process when this code runs, the references behind those Label variables are still null/Nothing. So you're putting references to Nothing into your array.

To fix the code, move the initialization to the Form_Load event instead.

Joel Coehoorn
  • 362,140
  • 107
  • 528
  • 764
0

Try this one:

Dim Dicelbls(8) As Label
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
    Dicelbls = {lblP1Die0, lblP1Die1, lblP1Die2, lblP2Die0, lblP2Die1, lblP2Die2, lblP1Score, lblP2Score}
End Sub
npk
  • 1,057
  • 10
  • 21
0

Try to add initialization in Form_Load event.

Dim Dicelbls As Label()

Private Sub Form1_Load(..)
  Dicelbls= new Label() {lblP1Die0, lblP1Die1, lblP1Die2, lblP2Die0, lblP2Die1, lblP2Die2, lblP1Score, lblP2Score}
....
End Sub
kv-prajapati
  • 90,019
  • 18
  • 141
  • 178
0

You're declaring the array correctly, but in the wrong place. Leave the variable declaration where it is, and move the assignment to somewhere after the form is created.

Class frmMain

    Dim Dicelbls As Label()

    Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dicelbls = {lblP1Die0, lblP1Die1, lblP1Die2, lblP2Die0, lblP2Die1, lblP2Die2, lblP1Score, lblP2Score}
    End Sub

    ...

End Class
Hand-E-Food
  • 11,154
  • 8
  • 40
  • 75