C# TreeView複製所有Node(使用遞迴「Recursive」方式)到另一個TreeView中 『 Copy all treeView parent and children to another treeView c# WinForms 』

C# TreeView複製所有Node(使用遞迴「Recursive」方式)到另一個TreeView中 『 Copy all treeView parent and children to another treeView c# WinForms 』

C# TreeView複製所有Node(使用遞迴「Recursive」方式)到另一個TreeView中 『 Copy all treeView parent and children to another treeView c# WinForms 』


資料來源: https://stackoverflow.com/questions/5619763/copy-all-treeview-parent-and-children-to-another-treeview-c-sharp-winforms

        private void Form1_Load(object sender, EventArgs e)
        {
            //添加一个节点,这个结点是根节点。  
            TreeNode node = new TreeNode();
            node.Text = "hope";
            treeView1.Nodes.Add(node);

            TreeNode node1 = new TreeNode();
            node1.Text = "hopeone";
            TreeNode node11 = new TreeNode();
            node11.Text = "hopeoneone";
            TreeNode node2 = new TreeNode();
            node2.Text = "hopetwo";

            node1.Nodes.Add(node11);//在node1下面在添加一个结点。  

            node.Nodes.Add(node1);//node下的两个子节点。  
            node.Nodes.Add(node2);


            TreeNode t = new TreeNode("basil");//作为根节点。  
            treeView1.Nodes.Add(t);
            TreeNode t1 = new TreeNode("basilone");
            t.Nodes.Add(t1);
            TreeNode t2 = new TreeNode("basiltwo");
            t.Nodes.Add(t2);

            TreeNode newTn;
            foreach (TreeNode tn in treeView1.Nodes)
            {
                newTn = new TreeNode(tn.Text, tn.ImageIndex, tn.SelectedImageIndex);
                if (tn.Nodes.Count > 0)
                {
                    CopyChildren(newTn, tn);
                }
                comboBoxTree1.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);
                if (tn.Nodes.Count > 0)
                {
                    CopyChildren(newTn, tn);
                }
            }
        }

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *