-2

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?

Spyrex
  • 103
  • 8
  • "What is a NullReferenceException, and how do I fix it?" would not have helped me in this case. – Spyrex Oct 14 '20 at 06:52

1 Answers1

0

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);
}
Gusman
  • 14,905
  • 2
  • 34
  • 50
  • Thank you for responding, but firstly Nodes is already an array so you do not have to call ToArray() and secondly the error is still the same then :( – Spyrex Oct 13 '20 at 20:51
  • @Spyrex `Nodes` is not an array, is a collection, more concretely a `TreeNodeCollection`, and you haven't tested it as the code has a missing piece `Cast` and without it you can't compile it. Try the updated answer. – Gusman Oct 13 '20 at 21:34
  • Oh sorry, I was a bit hasty with my answer. Thank you for the correction now it works. – Spyrex Oct 14 '20 at 06:38