Deep copying tree nodes

I am trying to copy treeview nodes to a treenodecollection for some other processing. When I execute treeview.nodes.clear() on the next line, my treenodecollection becomes null. Could you tell me how to copy tree nodes to a treenodecollection and save copies of nodes even after calling the Clear method of the actual tree nodes?

 TreeNodeCollection tnc = null; private TypeIn() { tnc = treeView1.Nodes; treeView1.Nodes.Clear(); //Now my tnc becomes null, but I want the tnc for future use. } 
+6
c #
source share
2 answers

The TreeNode object is cloned with the entire subtree. That is why you can use a List that will contain root nodes with subtrees there.

 List<TreeNode> tnc = null; private TypeIn() { tnc = new List<TreeNode>(); foreach (TreeNode n in treeView1.Nodes) { tnc.Add((TreeNode)n.Clone()); } treeView1.Nodes.Clear(); } 
+3
source share

You can get a deep copy by serializing the TreeView tree and deserializing it as a new object.

Take a look at this: How do you make a deep copy of an object in .NET (like C #)?

0
source share

All Articles