本文实例讲述了C#实现TreeView节点拖拽的方法。分享给大家供大家参考。具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
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);
}
} |
希望本文所述对大家的C#程序设计有所帮助。