C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
treeView1.AllowDrop = true;
treeView1.ItemDrag += new ItemDragEventHandler(treeView1_ItemDrag);
treeView1.DragEnter += new DragEventHandler(treeView1_DragEnter);
treeView1.DragDrop += new DragEventHandler(treeView1_DragDrop);
}
void treeView1_DragDrop(object sender, DragEventArgs e)
{
TreeNode moveNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");
//根据鼠标坐标确定要移动到的目标节点
Point pt;
TreeNode targeNode;
pt = ((TreeView)(sender)).PointToClient(new Point(e.X, e.Y));
targeNode = this.treeView1.GetNodeAt(pt);
//如果目标节点无子节点则添加为同级节点,反之添加到下级节点的未端
TreeNode NewMoveNode = (TreeNode)moveNode.Clone();
if (targeNode.Nodes.Count == 0)
{
targeNode.Parent.Nodes.Insert(targeNode.Index, NewMoveNode);
}
else
{
targeNode.Nodes.Insert(targeNode.Nodes.Count, NewMoveNode);
}
//更新当前拖动的节点选择
treeView1.SelectedNode = NewMoveNode;
//展开目标节点,便于显示拖放效果
targeNode.Expand();
//移除拖放的节点
moveNode.Remove();
}
void treeView1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode"))
{
e.Effect = DragDropEffects.Move;
}
else
{
e.Effect = DragDropEffects.None;
}
}
void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
DoDragDrop(e.Item, DragDropEffects.Move);
}
}
private void Form1_Load(object sender, EventArgs e)
{
treeView1.LabelEdit = true;//可编辑状态。
//添加一个节点,这个结点是根节点。
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);
}
}
}