1

New to VB.net, frustrated have been looking at this all day, Why PbAlly() value is Nothing ?

my screenshoot :

Null Reference Exception error

Code look like :

Public Class Form1
Dim thdUDPServer
Dim Playing As Boolean = False
Dim Giliran As Boolean = False

Dim PbAlly() As PictureBox = {pbAlly1, pbAlly2, pbAlly3, pbAlly4, pbAlly5, pbAlly6, pbAlly7}

Dim Kartu As Integer = 0

Public Sub initGame()
    Dim RandomClass As New Random()
    Dim RememberSet As New HashSet(Of Integer)

    Dim RandomNumber As Integer

    While RememberSet.Count < 7
        RandomNumber = RandomClass.Next(1, 14)
        If RememberSet.Add(RandomNumber) Then
            If RandomNumber = 11 Then
                lbData.Items.Add("*J")
            ElseIf RandomNumber = 12 Then
                lbData.Items.Add("*Q")
            ElseIf RandomNumber = 13 Then
                lbData.Items.Add("*K")
            Else
                lbData.Items.Add("*" & RandomNumber)
            End If
            PbAlly(Kartu).Image = Card.My.Resources.ResourceManager.GetObject(RandomNumber)
            Kartu += 1
        End If
    End While
End Sub

PbAlly() always giving me a null reference exception and I don't know why ?

Thanks for the help in advance.

trashr0x
  • 6,457
  • 2
  • 29
  • 39
Yoshi
  • 11
  • 1
  • Where is pbAlly1 through 7 defined? – Prescott Chartier Nov 11 '17 at 20:50
  • You are trying to store controls in the array before they have been created. See the dupe link. Also your app will leak using resource images that way...and you should probably define your random generator as a form level var – Ňɏssa Pøngjǣrdenlarp Nov 12 '17 at 00:36
  • Because when you declare an array like pbAlly().... and so on, it only creates the array with the number of elements that you assign to it. Your random number generator generates numbers from 1 to 13 (yes 13) and when you try to assign an image to an element that has not been created, sat pbAlly(13), you'll get a null reference exception – David Wilson Nov 12 '17 at 08:51

0 Answers0