65.9K
CodeProject is changing. Read more.
Home

Drag & Drop in Tree view

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.86/5 (51 votes)

Jun 4, 2003

1 min read

viewsIcon

199204

downloadIcon

4545

This is basically an article which demonstrates the Drag & Drop operation in a TreeView.

Sample Image - TreeDragnDrop.jpg

Introduction

I needed drag 'n' drop facility in TreeView control, which I guess is quite a common functionality. But I couldn't find it, so I implemented it.

Thinking it might be useful to other people, I am sharing the code here.

Implementation

In this app, I have provided the functionality to add children or siblings to a node via toolbar.

Events that are required to be implemented are:

  1. ItemDrag
  2. DragDrop
  3. DragEnter

of the TreeView control.

In DragItem event, simply store the selected node that is the node to be dragged, in a TreeNode type class variable & call DoDragDrop as shown below:

NodeToBeDeleted = (TreeNode)e.Item;
   string strItem = e.Item.ToString();
   DoDragDrop(strItem, DragDropEffects.Copy | DragDropEffects.Move);

In DragEnter, set appropriate effects.

In DragDrop, do the following steps:

  1. Get the current mouse position, that is coordinates where to drop the dragged node.
  2. Use PointToClient method of the TreeView control to get the coordinates relative to the TreeView control.

  3. Get the node at this position (that is the node on which to drop the dragged node)
  4. Then delete the node dragged from its current position & insert it at the next index of the node at which to drop. That's it.
Position.X = e.X;
   Position.Y = e.Y;
   Position = treeView1.PointToClient(Position);
   TreeNode DropNode = this.treeView1.GetNodeAt(Position);
   if (DropNode != null && DropNode.Parent == this.NodeToBeDeleted.Parent )
   {
    TreeNode DragNode = this.NodeToBeDeleted;
    DropNode.Parent.Nodes.Remove(this.NodeToBeDeleted);
    DropNode.Parent.Nodes.Insert(DropNode.Index+1, DragNode);
   }

Now the code is ready to be executed

Conclusion

I hope it helps u ppl. All the best.

Do give feedback on this article as positive criticism is always healthy for growth.