Traversing TreeNodes to find the highest level parents Tag data, how to save initial TreeNodes info?

StackOverflow https://stackoverflow.com/questions/23503206

  •  16-07-2023
  •  | 
  •  

سؤال

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
}
هل كانت مفيدة؟

المحلول

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top