如何在visual basic.net中使用Label对象初始化数组

时间:2011-10-04 02:54:56

标签: vb.net visual-studio

http://pastebin.com/3A4P61Gt有问题的代码专门在第143行。每当我尝试访问数组中的标签时,如Dicelbls(0).Text,我得到一个空引用错误。显然我没有声明阵列正确,有什么建议吗?

4 个答案:

答案 0 :(得分:1)

你是对的,问题出在第143行:

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

具体来说,在此代码运行时,在对象初始化过程中,这些Label变量后面的引用仍为null / Nothing。所以你要把Nothing的引用放到你的数组中。

要修复代码,请将初始化移至Form_Load事件。

答案 1 :(得分:0)

尝试在Form_Load事件中添加初始化。

Dim Dicelbls As Label()

Private Sub Form1_Load(..)
  Dicelbls= new Label() {lblP1Die0, lblP1Die1, lblP1Die2, lblP2Die0, lblP2Die1, lblP2Die2, lblP1Score, lblP2Score}
....
End Sub

答案 2 :(得分:0)

你正确地声明了数组,但是在错误的地方。将变量声明保留在原始位置,并在创建表单后将赋值移动到某处。

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

答案 3 :(得分:0)

试试这个:

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