Windows Develop Bookmark and Share   
 index > Windows Forms General > Duplicating the contents of a treeView
 

Duplicating the contents of a treeView

Hello,

I have 2 treeView controls on my form. Can you please tell me how can I copy all the nodes with the same structure from treeView1 to treeView2?

Note: I'm using .NET 2005.

Your help would be greatly appreciated.
Angry Coder  Thursday, July 13, 2006 7:26 PM

You need to clone all the top-level nodes. This will do what you want:

destinationTreeView.Nodes.Clear();

foreach (TreeNode node in sourceTreeView.Nodes)

{

TreeNode newNode = node.Clone() as TreeNode;

destinationTreeView.Nodes.Add(newNode);

}

Peter Ritchie  Monday, July 17, 2006 6:27 PM
This thread is off topic for the Visual C# General forum, moving to Windows Forms Genera.
Peter Ritchie  Thursday, July 13, 2006 9:09 PM

tv.Nodes.CopyTo(MyNodeArray, 0)

tv1.Nodes.AddRange(MyNodeArray)

DMan1  Monday, July 17, 2006 6:00 PM
DMan1 wrote:

tv.Nodes.CopyTo(MyNodeArray, 0)

tv1.Nodes.AddRange(MyNodeArray)

That will give you an exception with the message "Cannot add or insert the item 'somenodename' in more than one place. You must first remove it from its current location or clone it. As well, that only copies top-level nodes, it does not traverse the tree.
Peter Ritchie  Monday, July 17, 2006 6:18 PM

You need to clone all the top-level nodes. This will do what you want:

destinationTreeView.Nodes.Clear();

foreach (TreeNode node in sourceTreeView.Nodes)

{

TreeNode newNode = node.Clone() as TreeNode;

destinationTreeView.Nodes.Add(newNode);

}

Peter Ritchie  Monday, July 17, 2006 6:27 PM

You can use google to search for other answers

Custom Search

More Threads

• User Control hosting child controls via VS designer
• RadioBox CheckedChanged Event not firing
• Slow Window Drawing using Visual Studio 2005 and Windows Forms 2.0
• Dynamic add a Plugin to Project
• Unicode and Font family
• how to Select and get the contents of a row in a DataGridView
• Transparent background on an MDI Child...
• C# windows form application NumericUpDown questions
• Changes made in designer not propogating to code
• How to display welcome screen