Live Chat Icon For mobile
Live Chat Icon

How can I clone/copy all the nodes from one TreeView Control to another?

Platform: WinForms| Category: TreeView

The following code snippet demonstrates how you can clone or copy all the nodes in TreeView1 to TreeView2 by clicking on Button1.

private void  IterateTreeNodes (TreeNode originalNode, TreeNode rootNode)
		foreach( TreeNode childNode in  originalNode.Nodes)
			TreeNode newNode = new TreeNode(childNode.Text);		
			newNode.Tag = childNode.Tag;
			this.treeView2.SelectedNode = rootNode;
			IterateTreeNodes(childNode, newNode);

//Button Click code
private void button1_Click(object sender, System.EventArgs e)
		foreach( TreeNode originalNode in  this.treeView1.Nodes)
			TreeNode newNode = new TreeNode(originalNode.Text);
			newNode.Tag = originalNode.Tag;
			IterateTreeNodes(originalNode, newNode);

Private  Sub IterateTreeNodes(ByVal originalNode As TreeNode, ByVal rootNode As TreeNode)
		Dim childNode As TreeNode
		For Each childNode In originalNode.Nodes
			Dim NewNode As TreeNode =  New TreeNode(childNode.Text) 
			NewNode.Tag = childNode.Tag
			Me.treeView2.SelectedNode = rootNode
			IterateTreeNodes(childNode, NewNode)
End Sub
’Button Click code
Private  Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
		Dim originalNode As TreeNode
		For Each originalNode In Me.treeView1.Nodes
			Dim NewNode As TreeNode =  New TreeNode(originalNode.Text) 
			NewNode.Tag = originalNode.Tag
			IterateTreeNodes(originalNode, NewNode)
End Sub

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.