Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ForEach TreeNode.Nodes Pulls Out Null Node

I have two recursive methods that are meant to check/uncheck all of the TreeNodes in a .NET TreeView The methods are very simple:

private void SetAllNodes(TreeNode rootNode, bool value)
{
    rootNode.Checked = value;
    foreach (TreeNode node in rootNode.Nodes)
        SetAllNodes(node, value);
}

private void SetAllNodes(TreeView root, bool value)
{
    foreach (TreeNode node in root.Nodes)
        SetAllNodes(node, value);
}

I call it like this:

SetAllNodes(this.myTreeView, true);

Anyway, this has worked fine for some time, but all of a sudden, I got a null reference exception. After doing some debugging, I noticed during the foreach loop of the second function, at about the second iteration, a null TreeNode is returned.

Even more strangely, if I replace the foreach loop with the following code, the error goes away:

for (int i = 0; i < root.Nodes.Count; i++)
{
   TreeNode node = root.Nodes[i];
   SetAllNodes(node, value);
}

Any ideas why this is occurring? I've debugged as much as I can, but the simple fact is that I am getting a null item from my foreach loop.

Edit As requested, here is the stack trace:

MyProgram.exe!MyProgram.UI.frmFilter.SetAllNodes(System.Windows.Forms.TreeNode rootNode = null, bool value = false) Line 457 + 0x7 bytes    C#
MyProgram.exe!MyProgram.UI.frmFilter.SetAllNodes(System.Windows.Forms.TreeView root = {System.Windows.Forms.TreeView}, bool value = false) Line 450 + 0x6a bytes    C#
MyProgram.exe!MyProgram.UI.frmFilter.btnNone_Click(object sender = {Text = "None"}, System.EventArgs e = {X = 36 Y = 5 Button = Left}) Line 604 C#
[External Code] 
MyProgram.exe!MyProgram.Program.Main(string[] args = {string[0]}) Line 33 + 0x1d bytes  C#
[External Code]
like image 575
Eric Avatar asked Jun 16 '26 00:06

Eric


1 Answers

I would guess that rootNode.Checked = value is changing the structure of the internal collection, so the enumerator (foreach) is somehow returning a reference to a node that moved. Ideally an InvalidOperationException would be thrown with the message "collection was modified." Without a better understanding of what the Checked property setter is doing, using a for loop is probably a good work around.

like image 67
Robin Avatar answered Jun 18 '26 14:06

Robin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!