gpt4 book ai didi

c# - NullReferenceException 未处理

转载 作者:太空宇宙 更新时间:2023-11-03 19:08:36 25 4
gpt4 key购买 nike

我正在制作一个 Windows 窗体应用程序,我正在其中动态添加一个 PictureBox。什么可能导致以下错误?

NullReferenceException was unhandled.

Use "new" keyword to create an object of instance

代码:

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]);
}

关于c# - NullReferenceException 未处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23337932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com