0

I have TreeNode object from my TreeView which is the currently selected Node. I would like to traverse this node to find its highest level parent and get some information from it (namely the data in its Tag variable).

How could I easily do this while keeping my inNode still equal to what it was then the function was passed it?

private void openNodeWindow(TreeNode inNode)
{
    // Find the top level window type this is in.
    TreeNode curNode = inNode; 
    WindowType topLevelType = WindowType.NO_WINDOW;

    // As long as there is a parent to this Node
    while (curNode.Parent != null && 
        // As long as that parent has a specified window type
        (WindowType)curNode.Parent.Tag != WindowType.NO_WINDOW)
    {
        topLevelType = (WindowType)curNode.Tag;
        curNode = curNode.Parent;
    }

    // Do stuff with the topLevelType variable now
    // Also having inNode set back to what it was originally
}
AnotherUser
  • 1,311
  • 1
  • 14
  • 35

1 Answers1

-1

Clone the object instead of setting a reference http://msdn.microsoft.com/en-us/library/system.windows.forms.treenode.clone(v=vs.110).aspx

// TreeNode curNode = inNode; // set by reference
TreeNode curNode = (TreeNode) inNode.Clone(); // clone (set by value)

Now when you modify the curNode object, the inNode should be unmodified.

EDIT this only seems to be shallow copy.

(from msdn TreeNode.Clone Method)

Remarks: The tree structure from the tree node being cloned and below is copied. Any child tree nodes assigned to the TreeNode being cloned are included in the new tree node and subtree.

The Clone method performs a shallow copy of the node. If the value of the Tag property is a reference type, both the original and cloned copy will point to the same single instance of the Tag value.

You could try to make a deep copy of the object, more reference of how here.

Or you could 'backup' the values you want to preserve and copy them back to the inNode object when you are done using curNode

Community
  • 1
  • 1
Kunukn
  • 2,136
  • 16
  • 16
  • This does not preserve the "graph" that the nodes make up. I cannot traverse `curNode` the same (or at all) like I would `inNode`. The parent of `curNode` is `null` when made in that manner. – AnotherUser May 07 '14 at 10:58
  • @user1596244 Ok, the clone didn't worked as I though i would then. The idea is the same. You make 'backup' of the values and use them later. – Kunukn May 07 '14 at 11:05
  • I have found a sneaky way around my problem. I just call `TreeView.GetSelectedNode` twice in my function, once to work on it as above, the second to use it later on. I just let the treeview do the work for me. Thanks for the help! – AnotherUser May 07 '14 at 11:39
  • -1 this shouldn't be marked as an answer as it's completely different from what the op is asking. Also, the example links are for deep cloning of objects, not cloning a TreeNode hierarchy. – Adam Plocher Jul 12 '14 at 10:23