首页 > 编程 > C# > 正文

C#实现TreeView节点拖拽的方法

2020-01-24 01:27:59
字体:
来源:转载
供稿:网友

本文实例讲述了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); }}

希望本文所述对大家的C#程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表