Domanda

I am making a windows form application where I am adding a PictureBox dynamically. What could be causing the following error?

NullReferenceException was unhandled.

Use "new" keyword to create an object of instance

Code:

PictureBox[] picArray = new PictureBox[allFiles.Length];
int y = 0;
for (int i = 0; i < picArray.Length; i++ )
{
    this.Controls.Add(picArray[i]);
    if(i%3 == 0){
        y = y + 150;
    }
    picArray[i].Location = new Point(i*120 + 20 , y);
    picArray[i].Size = new Size(100, 200);
    picArray[i].Image = Image.FromFile(allFiles[i]);
}
È stato utile?

Soluzione

You have initialized the array, not the PictureBoxes in it:

// all PictureBoxes in the array are null after the next statement:
PictureBox[] picArray = new PictureBox[allFiles.Length]; 
int y = 0;
for (int i = 0; i < picArray.Length; i++ )
{
    var newPictureBox = new PictureBox(); // this will initialize it 
    picArray[i] = newPictureBox;  // this will add it to the array 
    this.Controls.Add(newPictureBox);
    if(i%3 == 0){
        y = y + 150;
    }
    newPictureBox.Location = new Point(i*120 + 20 , y);
    newPictureBox.Size = new Size(100, 200);
    newPictureBox.Image = Image.FromFile(allFiles[i]);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top