我正在创建一个Windows表单应用程序,我在其中动态添加PictureBox
。可能导致以下错误的原因是什么?
NullReferenceException未处理。
使用" new"用于创建实例对象的关键字
代码:
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]);
}
答案 0 :(得分:6)
您已初始化数组,而不是其中的PictureBoxes
:
// 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]);
}