简体   繁体   中英

C# nullReferenceException while adding items to array

I get this error when I try to add items to an array, it adds with no problem 1 items, but when there are more it stops and gives an error.

nullReferenceException Object reference not set to an instance of an object.

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

here is a pic to show that the fi(FileInfo) and di(DirectoryInfo) are not empty: 在此输入图像描述

It looks to me that you never initialize the OpenFiles array items - that is, you only initialize the first item.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM