当我尝试将项目添加到数组时,我收到此错误,它会添加1个项目没有问题,但是当有更多项目停止并出错时。
的NullReferenceException 对象引用未设置为对象的实例。
public void btnZoek_Click(object sender, EventArgs e)
{
if (search == false)
{
OpenFiles[index] = new AddFileClass();
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Application.StartupPath + "\\Saves");
System.IO.FileInfo[] rgFiles = di.GetFiles("*.txt");//add only .txt files
foreach (System.IO.FileInfo fi in rgFiles)
{
OpenFiles[index].setNewItem(index, fi.Name, Convert.ToString(di));//send the info to the array (Number, filename, filelocation)
index++;
}
search = true; //make sure it doens'nt add something double
}
if (search == true)
{
Form3_Zoeken_ frmSearch = new Form3_Zoeken_();
frmSearch.Show();
}
}
这是一张照片,显示fi(FileInfo)和di(DirectoryInfo)不为空:
答案 0 :(得分:2)
在我看来,你永远不会初始化OpenFiles数组项 - 也就是说,你只是初始化第一项。
试试这个:
public void btnZoek_Click(object sender, EventArgs e)
{
if (search == false)
{
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Application.StartupPath + "\\Saves");
System.IO.FileInfo[] rgFiles = di.GetFiles("*.txt");//add only .txt files
foreach (System.IO.FileInfo fi in rgFiles)
{
OpenFiles[index] = new AddFileClass();
OpenFiles[index].setNewItem(index, fi.Name, Convert.ToString(di));//send the info to the array (Number, filename, filelocation)
index++;
}
search = true; //make sure it doens'nt add something double
}
if (search == true)
{
Form3_Zoeken_ frmSearch = new Form3_Zoeken_();
frmSearch.Show();
}
}