0

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: enter image description here

2
  • 3
    Are we supposed to guess what all your classes do, which line causes the exception and which variable is null? This game gets harder every day! Commented Sep 14, 2011 at 8:51
  • Shot in the blue: I think OpenFiles[index] in foreach contains null and not an instance. Commented Sep 14, 2011 at 8:52

1 Answer 1

2

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.