How do I initialize an array with Label objects in visual basic.net
http://pastebin.com/3A4P61Gt The code in question is specifically at line 143. Whenever I try to ac开发者_运维技巧cess 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?
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.
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
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
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
精彩评论