Search code examples
c#.nettreeviewrootchildren

System.NullReferenceException when making all root node's children to root nodes


To remove the root node without it's children I wrote the following loop:

foreach (TreeNode n in treeView_Chpters.Nodes[0].Nodes)
{
    treeView_Chpters.Nodes.Remove(n);
    treeView_Chpters.Nodes.Add(n);
}

But if the root node has more children than one, I get an error that says, that n is null. How can I fix this?


Solution

  • You are modifying a collection while you are iterating it, that will cause an exception for sure.

    In order to avoid that, extract the nodes as an array and then iterate it:

    var nodes = treeView_Chpters.Nodes[0].Nodes.Cast<TreeNode>().ToArray();
    
    foreach (TreeNode n in nodes )
    {
        treeView_Chpters.Nodes.Remove(n);
        treeView_Chpters.Nodes.Add(n);
    }