-1

I'm a beginner on visual basic, and I'm working on this game, it's supposed to load the images that are stored in the picture box array and show them randomly, but I keep getting the runtime error "NullReferenceException" in this line:

 if(egypt[randomNumber]==egypt[0])

The lines before were:

PictureBox [] egypt = new PictureBox [5];
Image egypt1 = Image.FromFile(Application.StartupPath + @"\image\egypt1.png");
egypt[0].Image = egypt1;

Thank you.

Boshokai
  • 3
  • 1
  • 7

2 Answers2

1

I suspect the error is actually on the egypt[0].Image = egypt1 line because there is a bug in Visual Studio that means that occasionally the Exception Assistant highlights the line after the one that threw the exception.

Anyway...

egypt[0] is null because you have not yet assigned an actual object to it. You have only reserved the space for the array but not put anything in there (the array is full of nulls when created)

You need to add aline before it so it reads something like this:

egypt[0] = new PictureBox(); // This is the new line
egypt[0].Image = egypt1;     // This is the existing line

I suspect this will solve your problem.

Colin Mackay
  • 18,736
  • 7
  • 61
  • 88
0

You have to create an instance of the pictuebox and assign it to the array - by writing

  egypt[0].Image = egypt1;

you are trying to access the .Image property of a PictureBox at pos 0 in an empty array. egypt[0] has the value of NULL. Assign a instance of that object by adding the following line before...

   egypt[0] = new PictureBox();

Btw: I dont know your specific case, but i would not create an array of Pictueboxes, better load the images into an array or Imagelist and assign them to the picture box when needed... Except if you want to display each of them at the same time ;)

Cadburry
  • 1,844
  • 10
  • 21