Question Treeview: only allow children to parent node, no children of children

sous2817

Member
Joined
Apr 5, 2011
Messages
17
Programming Experience
Beginner
Hello everyone,

I'm working on a drag-and-drop method to copy items from a listview control to a treeview. I've got the drag and drop working, but I'm hoping to limit the ability to drag items that create a child of a child. Ideally, if someone drags an item from the listview to the Treeview and the drop the listview item over a child, it would drop the dragged item to the parent.

Hope I've explained it and any help is appreciated.

Thanks in advance
 
Use the DragOver event and hittest current location against the node level, this will provide proper feedback to the user about where drops is allowed, for example:
VB.NET:
Dim pt = Me.ATreeView.PointToClient(New Point(e.X, e.Y))
Dim node = Me.ATreeView.GetNodeAt(pt)
If node IsNot Nothing AndAlso node.Level = 0 Then
    e.Effect = DragDropEffects.Copy
Else
    e.Effect = DragDropEffects.None
End If
Same GetNodeAt code in DragDrop to find the root node to add node to.
 
Thank you for the code JohnH,

This is my hack that seemed to work as well:

VB.NET:
Dim position As New Point(0, 0)
Dim oparent As TreeNode
Dim dNode As TreeNode
position.X = e.X
position.Y = e.Y
position = Tree1.PointToClient(position)
oparent = Tree1.GetNodeAt(position)
If IsNothing(oparent) Then
     Exit Sub
Else
 
Dim node As TreeNode = oparent
 
If node.Parent IsNot Nothing Then
     node.Parent.Nodes.Add(lbSource.SelectedItems(0).Text)
Else
oparent.Nodes.Add(lbSource.SelectedItems(0).Text)
End If
End If

Your way is way cleaner...

Thanks again!
 
Back
Top