0
votes

I have a TreeView that is empty at application start. Nodes are dynamically added, and for each node I put its tag into a dictionary.

Now, if I have many long branches of nodes and I delete the root node and its tag from the dictionary, then of course the child nodes tags will stay in the dictionary.

So I tried this:

foreach(TreeNode tn in treeView.SelectedNode.Nodes)
{
    dictionary.Remove((string)tn.Tag); // remove all respective keys
}
dictionary.Remove((string)treeView.SelectedNode.Tag); // remove the selected node's key
treeView.Nodes.Remove(treeView.SelectedNode); // remove the selected node itself

But this only deletes the selected node and the first child node. Is there a way to do this recursively, from the top of a tree to the root, so that each key gets savely removed?

1
Why you need Dictionary?Renatas M.
@Reniuz Obviously to keep track of which nodes are created and which are deleted by the user, as the trees represent some kind of conversation structure, where each key in the dictionary contains relevant input/output info.betaFlux
So your dictionary is mirror of tree? So why not store node relevant data in node tag?Renatas M.
Well, that's a neat idea! I'll have a look at that. Thanks!betaFlux

1 Answers

1
votes
//add new method

private void DeleteDictionaryEntries(TreeNode tn)
{
    foreach(TreeNode child in tn.Nodes)
       DeleteDictionaryEntries(child);
    dictionary.Remove((string)tn.Tag);
}

//in your method
DeleteDictionaryEntries(treeView.SelectedNode);
treeView.Nodes.Remove(treeView.SelectedNode); // remove the selected node itself