0

I know that this error is shown where object is null. But in my case I'm not sure why is it shown. I tried to create 10 PictureBox objects on every 30px of width randomly, on timer_tick and here is my code.

PictureBox[] meteor;
int i=0;
Random rnd = new Random();

private void timer1_Tick(object sender, EventArgs e)
{
    if(i<10)
    { 
    int pozicija = rnd.Next(1, 25);
    pozicija *= 30;
    meteor[i] = new PictureBox()
    {
        Name = "pictureBox",
        BackColor = Color.Transparent,
        Size = new Size(80, 60),
        Location = new Point(pozicija, 0),
        Image = imageList2.Images[0],
    };
    this.Controls.Add(meteor[i]);
    }
    i++;
}

Error is pointed to this line of code

this.Controls.Add(meteor[i]);

Why Visual studio shows this error?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Danilo Ivanovic
  • 1,216
  • 1
  • 10
  • 18

1 Answers1

1

You must instantiate the array first before using it, like this:

PictureBox[] meteor = new PictureBox[10];

Also I'm assuming that imageList2 has been defined and you have added an image to it.