Dragdrop應用 - in TreeView

目的:

TreeView內節點拉動變更位置

目的:

TreeView內節點拉動變更位置

程式碼:

 


        private void USetList_DragDrop(object sender, DragEventArgs e)
        {
            Point pt = PointToClient(new Point(e.X, e.Y));
            TreeNode DestinationNode = USetList.GetNodeAt(pt);
            Int32 iDesPos = -1;
            if (DestinationNode != null)
                iDesPos = DestinationNode.Index;

            if (e.Data.GetDataPresent(typeof(TreeNode)))
            {
                if (e.Effect == DragDropEffects.Copy)
                {
                    TreeNode tmpTN = (TreeNode)srcNodeForDrag.Clone();
                    if (iDesPos != -1)
                    {
                        DestinationNode.Parent.Nodes.Insert(iDesPos, tmpTN);
                    }
                }
                else if (e.Effect == DragDropEffects.Move)
                {
                    bool bIsAdd = false;
                    TreeNode tmpTN = (TreeNode)srcNodeForDrag.Clone();
                    if (iDesPos != -1)
                    {
                        if (pt.X >= DestinationNode.Bounds.Left)
                        {
                            DestinationNode.Parent.Nodes.Insert(iDesPos, tmpTN);
                            bIsAdd = true;
                        }
                    }
                    if (!bIsAdd)
                    {
                        return;
                    }
                    srcNodeForDrag.Remove();
                }
            }

        }

        private void USetList_DragOver(object sender, DragEventArgs e)
        {
            if ((e.KeyState & 8) == 8 &&
                (e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
            {
                // CTL KeyState for copy.
                e.Effect = DragDropEffects.Copy;
            }
            else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move)
            {
                e.Effect = DragDropEffects.Move;
            }
        }

        private void USetList_ItemDrag(object sender, ItemDragEventArgs e)
        {
            srcNodeForDrag = (TreeNode)e.Item;
            if (srcNodeForDrag.Level == 2 || srcNodeForDrag.Level == 1)
                this.DoDragDrop(e.Item, DragDropEffects.All);
        }
注意事項:
AllowDrop = True