ColinOL

A Small Website

用户工具

站点工具


wiki:csharp:winform-sjd-td-yd-cz

树节点的拖动移动操作

void InitTreeviewDragable()
{
    this.treeView1.AllowDrop = true;
    this.treeView1.ItemDrag += new ItemDragEventHandler(treeView1_ItemDrag);
    this.treeView1.DragEnter += new DragEventHandler(treeView1_DragEnter);
    this.treeView1.DragDrop += new DragEventHandler(treeView1_DragDrop);    
}
void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    { 
        DoDragDrop(e.Item, DragDropEffects.Move);
    }
}
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_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);    
    }        
    //更新当前拖动的节点选择  
    this.treeView1.SelectedNode = NewMoveNode;       
    //展开目标节点,便于显示拖放效果         
    targeNode.Expand();           
    //移除拖放的节点         
    moveNode.Remove();
}
wiki/csharp/winform-sjd-td-yd-cz.txt · 最后更改: 2018/02/03 20:42 (外部编辑)