2015-03-31 69 views
1

我想創建一個簡單的遊戲,首先它需要隨機加載16個圖片框與圖像。我不確定問題出在哪裏。試圖分配圖片到VB中的圖片框

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 

我上線一個NullReferenceException錯誤之後案例X任何人都知道我做錯了嗎?

+0

你沒有說什麼不順心或者我得到一個什麼樣的錯誤是 – Plutonix 2015-03-31 22:15:40

+0

在案例X之後的行上的NullReferenceException錯誤 – ShinigamiMachine 2015-03-31 22:33:38

+0

可能重複[什麼是NullReferenceException,我該如何解決它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how- do-i-fix-it) – Plutonix 2015-03-31 22:36:33

回答

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的陣列。結果是NullReferenceException,因爲Nothing沒有Image屬性。

可以聲明有數組,但你只可以在窗體的構造函數運行(Sub New)後初始化它。窗體的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

+0

哦,哦,現在我明白了,我意識到這是多麼愚蠢。謝謝! – ShinigamiMachine 2015-03-31 22:36:56

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