-1

I don't understand what I'm doing wrong but I'm getting this error when trying to loop through this array of picturebox creations. Thus, I've used the try and catch to narrow it down, but still I don't know what's wrong?

private System.Windows.Forms.PictureBox[] imgVictim = new PictureBox[3]; //array for victim images
public void victimsRun()
{
    victimTimer.Enabled = true; //starts the timer

    PictureBox[] victim = new PictureBox[3];
    for (int i = 0; i < imgVictim.Length; i++) // 0 - 2
    {

        try
        {
            imgVictim[i].Image = Image.FromFile("victim" + i.ToString() + ".png");
        }
        catch (NullReferenceException)
        {
            MessageBox.Show("NULL EXECEPTION!");
        }
        MessageBox.Show(i.ToString());
    }
}

Could anyone at all help me?

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
Harry
  • 25
  • 3
  • 3
    Creating an array of 3 picturebox doesn't mean that you have created 3 picturebox. – Steve Nov 05 '15 at 16:08
  • 2
    Hint: How many `PictureBox` *instances* do you believe the code you've shown creates? Where are you calling any `PictureBox` constructors? – Jon Skeet Nov 05 '15 at 16:10
  • I didn't create any constructors for PictureBox, is it required? Thanks for the fast response thought. – Harry Nov 05 '15 at 16:18

1 Answers1

1

You need to create each PictureBox before using it

imgVictim[i] = new PictureBox();

Try this

private System.Windows.Forms.PictureBox[] imgVictim = new PictureBox[3]; //array for victim images
public void victimsRun()
{
    victimTimer.Enabled = true; //starts the timer
    string fileName = "";
    PictureBox[] victim = new PictureBox[3];
    for (int i = 0; i < imgVictim.Length; i++) // 0 - 2
    {
        try
        {
            fileName = "victim" + i.ToString() + ".png";
            if (System.IO.File.Exists(fileName))
            {
                imgVictim[i] = new PictureBox();
                imgVictim[i].Image = Image.FromFile("victim" + i.ToString() + ".png");
            }
            else
            {
                // file does not exist or needs a path in front of it
            }
        }
        catch (NullReferenceException)
        {
            MessageBox.Show("NULL EXECEPTION!");
        }
    }
}
Karen Payne
  • 1,799
  • 2
  • 10
  • 18