本文實例講述了C#實現TreeView節點拖拽的方法。分享給大家供大家參考。具體如下:
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);
}
}