Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

DnD with custom treenodes

I was wondering if someone could help me with implementing Drag & Drop of custom node objects in a TreeView control. I'm using the treeview to hold nNodes which are a subclass of TreeNode.

I wish to allow the user to drag & drop these treenodes around the treeview control.
I attached the dnd eventhandlers via:
this.nTreeView.DragEnter += new DragEventHandler(this.treeView_DragEnter);
this.nTreeView.ItemDrag += new ItemDragEventHandler(this.treeView_ItemDrag);
this.nTreeView.DragDrop += new DragEventHandler(this.treeView_DragDrop);

private void treeView_ItemDrag(object sender, System.Windows.Forms.ItemDragEventArgs e)
{
  NNode nnItem = (NNode)e.Item;
  DoDragDrop(nnItem, DragDropEffects.Copy |  DragDropEffects.Move);                        
}

private void treeView_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
  Point Position = new Point(0, 0);
  NNode dummy = new N("","");
  if (e.Data.GetData(dummy.GetType())!=null)
  {
    dummy = (NNode)(e.Data.GetData(dummy.GetType()));
  }
  else
  {
    dummy.MyNote.NoteTitle = "New Node";
    dummy.MyNote.NoteText = (string)e.Data.GetData("dummy".GetType());
  }            
  Position.X = e.X;
  Position.Y = e.Y;
  // Convert from Form Coordinates to treeView Client coordinates
  Position = this.notesTreeView.PointToClient(Position);
  nN_selected = (NotesNode)notesTreeView.GetNodeAt(Position);
  // add tree node
  (nN_selected).Nodes.Add(new NNode(dummy.MyNote.NoteTitle, dummy.MyNote.NoteText));
}

This works, but it isn't quite what I want. In the method treeView_DragDrop, for the last line where I'm adding the node, instead of
(nN_selected).Nodes.Add(new NNode(dummy.MyNote.NoteTitle, dummy.MyNote.NoteText));
I want to just use (nN_selected).Nodes.Add(dummy); so that the children will be added as well, but for some reason, this doesn't work.
Does anyone have any ideas why?

Supercytro
Tuesday, December 17, 2002

Have you tried removing the node from its previous position in the tree?

According to the documentation you must either remove a node from its previous position or clone it before you can add it to a new location.

Samuel D. Jack
Friday, December 20, 2002

*  Recent Topics

*  Fog Creek Home