Search code examples
c#treeviewtree-nodes

preventing duplicates when inserting nodes to treeview control


I want to create a hierarchical view of strings based on first two characters.

If the strings are: AAAA,AAAA,BBDD,AABB,AACC,BBDD,BBEE

I want to reate a treeview that looks like this:

AA  
  AAAA  
  AABB
  AACC 
BB
  BBDD
  BBEE

I currently have some code that looks like this (inside a loop over the strings):

    TreeNode pfxNode;

    if (treeView1.Nodes[pfx]!=null) {
        pfxNode = treeView1.Nodes[pfx];
    }
    else {
        pfxNode = treeView1.Nodes.Add(pfx);
    }

    if (!pfxNode.Nodes.ContainsKey(string)) {
        pfxNode.Nodes.Add(string, string + " some info");
    }

For some reason this ends up with multiple "AA" nodes at the top level.
What am I missing?

please no pre-filtering of strings I want to be able to check if a specific treenode exists based on its key.

thanks


Solution

  • else {
        pfxNode = treeView1.Nodes.Add(pfx);
    }
    

    There's your mistake, you are forgetting to set the key of the tree node. So the next ContainsKey() won't find it. Fix:

        pfxNode = treeView1.Nodes.Add(pfx, pfx);