private void treeView1_ItemDrag(object sender, ItemDragEventArgs e) { DoDragDrop(e.Item, DragDropEffects.Move); } private void treeView1_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } private void treeView1_DragDrop(object sender, DragEventArgs e) { Point targetPoint = treeView1.PointToClient(new Point(e.X, e.Y)); TreeNode targetNode = treeView1.GetNodeAt(targetPoint); TreeNode draggedNode = (TreeNode)e.Data.GetData(typeof(TreeNode)); if (draggedNode == null) { return; } if (targetNode == null) { draggedNode.Remove(); treeView1.Nodes.Insert(targetNode.Index, draggedNode); } else { TreeNode parentNode = targetNode; if (!draggedNode.Equals(targetNode) && targetNode != null) { bool canDrop = true; while (canDrop && (parentNode != null)) { canDrop = !Object.ReferenceEquals(draggedNode, parentNode); parentNode = parentNode.Parent; } if (canDrop) { TreeNode treeNode = draggedNode.Parent; int index = draggedNode.Index; if (index < targetNode.Index) { return; } draggedNode.Remove(); treeNode.Nodes.Insert(targetNode.Index, draggedNode); targetNode.Remove(); treeNode.Nodes.Insert(index, targetNode); } } } treeView1.SelectedNode = draggedNode; } private void Form1_Load(object sender, EventArgs e) { treeView1.AllowDrop = true; }
测试结果: