Copy nodes of one treeview to another

  • Thread starter Thread starter PiotrKolodziej
  • Start date Start date
P

PiotrKolodziej

Hi
How to copy treeview.Nodes from one treeview to another.
Is this posible to do this in one line ? ( Calling some function )
 
I have found the answer ( if someone will need in the future ):

TreeNodeCollection myTreeNodeCollection = myTreeViewBase.Nodes;
// Create an array of 'TreeNodes'.
TreeNode[] myTreeNodeArray = new TreeNode[myTreeViewBase.Nodes.Count];
// Copy the tree nodes to the 'myTreeNodeArray' array.
myTreeViewBase.Nodes.CopyTo(myTreeNodeArray,0);
// Remove all the tree nodes from the 'myTreeViewBase' TreeView.
myTreeViewBase.Nodes.Clear();
// Add the 'myTreeNodeArray' to the 'myTreeViewCustom' TreeView.
myTreeViewCustom.Nodes.AddRange(myTreeNodeArray);
 
A function like this should do it.

void CopyNodes(TreeView from, TreeView to)
{
foreach (TreeNode node in from)
{
to.Nodes.Add(node.Clone());
}
}

HTH

Ciaran O'Donnell
 
That moves them, rather than copies them like you originally requested. If
that is what you want to do then use this as CopyTo uses Array.Copy which is
faster then just a loop.

Ciaran O'Donnell
 
Back
Top