C# WinForms - 在同一个 TreeViewControl 中拖放

标签 c# winforms drag-and-drop treeview

我正在尝试在同一控件中实现 TreeView 项目的拖放。

我希望能够将一个项目从一个节点移动到另一个节点。

这是我当前的代码,当我运行它时,我可以看到该项目已开始拖动,但 Windows 图标不允许将其拖放到控件上的任何节点。

我当前的代码

private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
{
    DoDragDrop(e.Item, DragDropEffects.Move);
}

private void treeView1_DragEnter(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.Move;
}

private void treeView1_DragDrop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(typeof(TreeNode)))
    {
        TreeNode sourceNode = e.Data.GetData(typeof(TreeView)) as TreeNode;

        var item = new TreeNode(sourceNode.Text);


        System.Drawing.Point pt = ((TreeView)sender).PointToClient(new System.Drawing.Point(e.X, e.Y));
        TreeNode DestinationNode = ((TreeView)sender).GetNodeAt(pt);

        DestinationNode.Nodes.Add(item);
        DestinationNode.Expand();
    }
}

最佳答案

只需将 treeView1_DragDrop 函数修改为:

private void treeView1_DragDrop(object sender, DragEventArgs e)
{
    // Retrieve the client coordinates of the drop location.
    Point targetPoint = treeView1.PointToClient(new Point(e.X, e.Y));

    // Retrieve the node at the drop location.
    TreeNode targetNode = treeView1.GetNodeAt(targetPoint);

    // Retrieve the node that was dragged.
    TreeNode draggedNode = (TreeNode)e.Data.GetData(typeof(TreeNode));

    // Confirm that the node at the drop location is not 
    // the dragged node and that target node isn't null
    // (for example if you drag outside the control)
    if (!draggedNode.Equals(targetNode) && targetNode != null)
    {
        // Remove the node from its current 
        // location and add it to the node at the drop location.
        draggedNode.Remove();
        targetNode.Nodes.Add(draggedNode);

        // Expand the node at the location 
        // to show the dropped node.
        targetNode.Expand();
    }
}

关于C# WinForms - 在同一个 TreeViewControl 中拖放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20915260/

相关文章:

c# - 我们如何将数据表的数据列的数据复制到另一个数据表?

.net - WebBrowser 控件作为用户界面

C#垂直制表符控件

jquery - 限制 html5 Canvas 内的移动?

c# - 如何从 webforms 应用程序中使用 web API 服务?

c# - LINQ - 复杂 xml 的分组依据

c# - 改进 WPF ListBox 多项目拖放

ruby - Watir - 拖放不起作用

c# - WebBrowser 通过 html 中的链接在内部存储的 html 资源之间导航

c# - Java 设计器脚本项目在 VB6 到 C# 转换中的作用是什么?