Copy all treeView parent and children to another treeView c# WinForms

前端 未结 4 1308
梦谈多话
梦谈多话 2020-12-17 21:32

I am trying to copy the entire tree (exactly all nodes) of a treeview (completely) to another treeview using this code:

        TreeNodeCollection myTreeNode         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-17 22:34

    Like MohD's answer, but with recursion to get all nodes. (Nodes of childnodes)

        public void CopyTreeNodes(TreeView treeview1, TreeView treeview2)
        {
            TreeNode newTn;
            foreach (TreeNode tn in treeview1.Nodes)
            {
                newTn = new TreeNode(tn.Text, tn.ImageIndex, tn.SelectedImageIndex);
                CopyChildren(newTn, tn);
                treeview2.Nodes.Add(newTn);
            }
        }
        public void CopyChildren(TreeNode parent, TreeNode original)
        {
            TreeNode newTn;
            foreach (TreeNode tn in original.Nodes)
            {
                newTn = new TreeNode(tn.Text, tn.ImageIndex, tn.SelectedImageIndex);
                parent.Nodes.Add(newTn);
                CopyChildren(newTn, tn);
            }
        } 
    

提交回复
热议问题