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?
-
1possible duplicate of What is a NullReferenceException in .NET?John Saunders– John Saunders2011-10-04 02:59:41 +00:00Commented Oct 4, 2011 at 2:59
-
Write a small code to debug/test arrays of label.KV Prajapati– KV Prajapati2011-10-04 03:04:44 +00:00Commented Oct 4, 2011 at 3:04
Add a comment
|
4 Answers
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.
Comments
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