尝试在VB中将图片分配给PictureBoxes

时间:2015-03-31 22:09:44

标签: vb.net visual-studio-2012

我正在尝试创建一个简单的游戏,首先它需要随机加载带有图像的16个PictureBox。我不确定问题出在哪里。

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

我在案例X之后的行上得到NullReferenceException错误。任何人都知道我做错了什么?

2 个答案:

答案 0 :(得分:1)

I get a NullReferenceException error on the line after Case X

您无法像这样初始化数组:

Public Class Form1

    Private picArrows() As PictureBox = {pic11, pic12, pic13, pic14,
                                     pic21, pic22, pic23, pic24,
                                     pic31, pic32, pic33, pic34,
                                     pic41, pic42, pic43, pic44}

表单尚未初始化,因此它及其上的所有控件尚未创建。因此,所有这些控件引用都将为Nothing,从而为您提供一个充满Nothing s的数组。结果是NullReferenceException,因为Nothing没有Image属性。

您可以在那里声明数组,但只能在表单构造函数运行后{em>初始化(Sub New)。 Form Load是个好地方:

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}

另见NullReference Exception in Visual Basic

答案 1 :(得分:0)

没有伴侣阵列的安排略有不同:

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