Treeview 節點拖曳

  • 3009
  • 0
  • c#
  • 2012-03-30

摘要:Treeview 節點拖曳

在藍色小舖找到一篇 Treeview 節點拖曳 的文章,但我比較習慣用C#,改寫了一下。

又發現有個缺點,若把父節點移到子節點之下,該節點及其所屬子節點都會消失,所以加上判斷機制。

 


        public Form1()
        {
            InitializeComponent();

            TreeNode treeNode1 = new TreeNode("Node1");
            TreeNode treeNode2 = new TreeNode("Node2");
            TreeNode treeNode3 = new TreeNode("Node3");
            TreeNode treeNode4 = new TreeNode("Node0", new TreeNode[] { treeNode1, treeNode2, treeNode3 });
            TreeNode treeNode5 = new TreeNode("Node6");
            TreeNode treeNode6 = new TreeNode("Node4", new TreeNode[] { treeNode5 });
            TreeNode treeNode7 = new TreeNode("Node5");
            this.treeView1.Nodes.AddRange(new TreeNode[] { treeNode4, treeNode6, treeNode7 });
            this.treeView1.ExpandAll();

            this.treeView1.DragDrop += new DragEventHandler(this.treeView1_DragDrop);
            this.treeView1.ItemDrag += new ItemDragEventHandler(treeView1_ItemDrag);
            this.treeView1.DragEnter += new DragEventHandler(treeView1_DragEnter);
        }

        void treeView1_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            DoDragDrop(e.Item, DragDropEffects.Move);
        }

        private void treeView1_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
            {
                Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));   //找出目前位置
                TreeNode destinationNode = ((TreeView)sender).GetNodeAt(pt);    //找出目的節點
                TreeNode moveNode = (e.Data.GetData("System.Windows.Forms.TreeNode")) as TreeNode;  //取出要移動的節點

                if (CheckForefather(moveNode, destinationNode)) //排除將父節點移到子節點的情況
                {
                    MessageBox.Show("error!");
                    return;
                }
                moveNode.Remove();  //移去要移動的節點
                destinationNode.Nodes.Add((TreeNode)moveNode.Clone());  //加到新節點之下
                destinationNode.ExpandAll();    //展開顯示
            }
        }

        private bool CheckForefather(TreeNode fatherNode, TreeNode childNode)
        {
            if (fatherNode.Equals(childNode))
                return true;
            foreach (TreeNode tn in fatherNode.Nodes)
            {
                if (CheckForefather(tn, childNode))
                    return true;
            }
            return false;
        }