Search code examples
c#listtreeview

Clearing a treeView crash


in a c# wpf application, Im loading a treeView from a list, it has a delete, edit, and add button used with information saved in a list from a textFile, it also has a update button which when clicked it clears the treeView and then reloads the textFile info into the list and then the lists into the treeView however whenever i click the update its crashes my file when it hits: treeView1.Items.Clear(); all the variables prior to the .Clear() lines at the start are lists, also the there are more if statements similar to this one if(i == 0) i just took them out cause they all work the same. Thanks

here is the event code for the updated button

private void buttonUpdate_Click(object sender, RoutedEventArgs e)
{

    name.Clear();
    description.Clear();
    dateStart.Clear();
    dateDue.Clear();
    status.Clear();
    priority.Clear();
    details.Clear();

    using (StreamReader sr = new StreamReader("TaskList.txt"))
    {
        int i = 0;
        while (!sr.EndOfStream)
        {
            //if its on the first line of a task
            if (i == 0)
            {
                name.Add(sr.ReadLine());
                ++i;
            }
            else if (i == 1)
            {
                description.Add(sr.ReadLine());
                ++i;
            }
            else if (i == 2)
            {
                dateStart.Add(sr.ReadLine());
                ++i;
            }
            else
            {
                details.Add(sr.ReadLine());
                i = 0;
            }
        }

        treeView1.Items.Clear();

        for (int j = 0; j < name.Count; ++j)
        {
            TreeViewItem taskTree = new TreeViewItem();
            taskTree.Tag = name[j];
            taskTree.Header = name[j];
            taskTree.Items.Add(description[j]);
            taskTree.Items.Add(dateStart[j]);
            taskTree.Items.Add(dateDue[j]);
            taskTree.Items.Add(status[j]);
            treeView1.Items.Add(taskTree);
        }
        sr.Close();
    }
}

Solution

  • After clearing the treeview, SelectedItem is null.