Search code examples
c#winformsfunctiondatagridviewtaglib-sharp

Function not working in Form Load, but works everywhere else


I'm using the function below to add items to a DataGridView.

void addFiles(List<string> files)
{
    foreach (var item in filesFound)
    {
        if (File.Exists(item))
         {
            fileList.Add(item);
            MessageBox.Show(item);
            string p = GetFolderPath(Personal) + @"\Music Database\";
            Directory.CreateDirectory(p);
            string file="";
            try
            {
                StreamReader read = new StreamReader(p + "musicdatabase.txt");
                file = read.ReadToEnd();
                read.Close();
            }
            catch (Exception e)
            {
                if (e.ToString().Contains(""))
                {
                    //add error code here later
                }
            }

            StreamWriter write = new StreamWriter(p + "musicdatabase.txt");
            write.WriteLine(file + item);
            write.Close();

            dataGridView1.Rows.Add(getTitle(item), getArtist(item), getDuration(item), item);
        }
        else
        {
            //add file not found error code here
        }
    }
}

The function works fine. It adds the details perfectly. getTitle();, getArtist(); and getDuration(); do what they say. They use TagLib# to get the details of audio files. The file path of the audio file gets written to a text file in the users documents.

The problem arises when I load the form: I read the text file as a whole, putting each line into a new index of List<string> textlist = new List<string>();. This is fine. The list has each line. I then run addFiles(textlist);. I launch the program and it loads, but nothing is added to the DataGridView.

I have a feeling it may be to do with the fact it might not be loaded when the Form_Load is triggered.

private void Form1_Load(object sender, EventArgs e)
{
    string p = GetFolderPath(Personal) + @"\Music Database\musicdatabase.txt";
    //MessageBox.Show(p);
    //MessageBox.Show(File.Exists(p).ToString());
    if (File.Exists(p))
    {
        string[] text = File.ReadAllLines(p);
        List<string> textlist = new List<string>();
        textlist = text.ToList();
        // -- THIS PROVES THE textlist LIST CONTAINS ITEMS --
        //foreach (var item in textlist)
        //{
        //MessageBox.Show(item);
        //MessageBox.Show(textlist[0]);
        //}
        //THIS IS THE PROBLEM
        addFiles(textlist);
     }
 }

Solution

  • Your problem is here:

        foreach (var item in filesFound)
    

    You are referencing what appears to be a global variable called filesFound, rather than the variable files that is passed to the function.