Question

Problem:

In the screenshot below, I have a node 300-9885-00X along with its TreeNodeCollection (in the red square). A little bit lower, we find the 300-9885-00X again, I want to insert the TreeNodeCollection that we found earlier, into that node ...

TreeView Nodes


Background Information

I have a recursive program that goes through AutoCAD / SolidEdge assemblies. It opens the documents and prints the assemblies, and their children, and so on (recursively) ...

  • Green color means it is printed
  • Orange means it has already been printed before, so we don't need to print it again...

Question:

How do we insert an existing TreeNodeCollection into a TreeNode?

Knowing:

  1. The location of the TreeNodeCollection
  2. The location of the node in which I want to insert the collection into

The following variable TreeNodes contains my collection. Must I loop through the collection in order to add its text? TreeCollectionAdd Error

Was it helpful?

Solution

You can't add a TreeNodeCollection to a Node. You must loop through the TreeNodeCollection and add the nodes individually like so:

For j As Integer = 0 To TreeNodes.Count - 1
    n.Nodes.Add(TreeNodes(j).Clone())
Next

Notice I used .Clone(). This is due to the insertion of an already existing node. You can't do that, you must either delete the existing one or clone it. In my case, I had to clone it.

OTHER TIPS

// Get the '_NodesCollection' from the '_parentNode' TreeNode.
TreeNodeCollection _Nodes = _parentNode.FirstNode.Nodes;

// Create an array of 'TreeNodes'.
TreeNode[] Nodes = new TreeNode[_Nodes.Count];

// Copy the tree nodes to the 'Nodes' array.
_Nodes.CopyTo(Nodes, 0);

// Remove the First Node & Children from the ParentNode.
_parentNode.Nodes.Remove(_parentNode.FirstNode);

// Remove all the tree nodes from the '_parentNode' TreeView.
_parentNode.Nodes.Clear();

// Add the 'Nodes' Array to the '_parentNode' ParentNode.
_parentNode.Nodes.AddRange(Nodes);

// Add the Child Nodes to the TreeView Control
TvMap.Nodes.Add(_parentNode);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top