定义一个TreeView 名字为TVdepartment,设置allowdrop为True
//移动代码
private void MiMoveUp_Click(object sender, EventArgs e) //向上移动
...{
//by 闫磊 Email:Landgis@126.com,yanleigis@21cn.com 2007.10.10
TreeNode Node = TVdepartment.SelectedNode;
TreeNode PrevNode = Node.PrevNode;
if (PrevNode != null)
...{
TreeNode NewNode = (TreeNode)Node.Clone();
if (Node.Parent == null)
...{
TVdepartment.Nodes.Insert(PrevNode.Index, NewNode);
}
else
...{
Node.Parent.Nodes.Insert(PrevNode.Index, NewNode);
}
Node.Remove();
TVdepartment.SelectedNode = NewNode;
}
}
private void MiMoveDown_Click(object sender, EventArgs e)//向下移动
...{
//by 闫磊 Email:Landgis@126.com,yanleigis@21cn.com 2007.10.10
TreeNode Node = TVdepartment.SelectedNode;
TreeNode NextNode = Node.NextNode;
if (NextNode != null)
...{
TreeNode NewNode = (TreeNode)Node.Clone();
if (Node.Parent == null)
...{
TVdepartment.Nodes.Insert(NextNode.Index + 1, NewNode);
}
else
...{
Node.Parent.Nodes.Insert(NextNode.Index + 1, NewNode);
}
Node.Remove();
TVdepartment.SelectedNode = NewNode;
}
}
//拖动代码
private void TVdepartment_ItemDrag(object sender, ItemDragEventArgs e)//左键拖动
...{
if (e.Button == MouseButtons.Left)
...{
DoDragDrop(e.Item, DragDropEffects.Move);
}
}
private void TVdepartment_DragEnter(object sender, DragEventArgs e)
...{
if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode"))
...{
e.Effect = DragDropEffects.Move;
}
else
...{
e.Effect = DragDropEffects.None;
}
}
private void TVdepartment_DragDrop(object sender, DragEventArgs e)//拖动
...{
//by 闫磊 Email:Landgis@126.com,yanleigis@21cn.com 2007.10.10
//获得拖放中的节点
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.TVdepartment.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);
}
//更新当前拖动的节点选择
TVdepartment.SelectedNode = NewMoveNode;
//展开目标节点,便于显示拖放效果
targeNode.Expand();
//移除拖放的节点
moveNode.Remove();
}
本文参考了:http://epasser.aydc.com.cn/article/adp/2-10-1/RSS%E9%98%85%E8%AF%BB%E5%99%A8%E5%88%B6%E4%BD%9C%E4%B9%8BTreeView%E6%A0%91%E8%8A%82%E7%82%B9%E7%A7%BB%E5%8A%A8%E6%93%8D%E4%BD%9C%E7%9A%84%E5%AE%9E%E7%8E%B0_-_12802.html