未对NullReferenceException进行索引
本文关键字:索引 NullReferenceException 未对 | 更新日期: 2023-09-27 18:00:34
我正在制作一个windows窗体应用程序,在其中动态添加一个PictureBox
。是什么原因导致了以下错误?
未处理NullReferenceException。
使用";新的";关键字来创建实例的对象
代码:
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]);
}
您已经初始化了数组,而不是其中的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]);
}