Live Chat Icon For mobile
Live Chat Icon

How do I implement Drag and Drop support between two TreeViews

Platform: WinForms| Category: TreeView

In a posting in the Microsoft.Windows.Forms newsgroup, Brian Roder (Microsoft) gives VB.Net code snippets to handle the DragEnter, ItemDrag and DragDrop events that provide a solution to this problem. You can get C# code in this sample, TreeViewDnD. Here is some sample handlers.

private void treeView2_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
  TreeNode newNode;
  if( e.Data.GetDataPresent(''System.Windows.Forms.TreeNode'', false))
  {
    Point pt;
    TreeNode destinationNode;
    pt = treeView2.PointToClient(new Point(e.X, e.Y));
    destinationNode = treeView2.GetNodeAt(pt);
    newNode = (TreeNode) e.Data.GetData(''System.Windows.Forms.TreeNode'');
    if(!destinationNode.Equals(newNode))
    {
      //destinationNode.Nodes.Add(newNode.Clone());
      destinationNode.Nodes.Add((TreeNode) newNode.Clone());
      destinationNode.Expand();
      //Remove original node
      newNode.Remove();
    }
  }
}

private void treeView2_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
   e.Effect = DragDropEffects.Move;
}

private void treeView2_ItemDrag(object sender, System.Windows.Forms.ItemDragEventArgs e)
{
  DoDragDrop(e.Item, DragDropEffects.Move);
}

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.