New to Telerik UI for WinForms? Download free 30-day trial

Cancel a Drag and Drop Operation

In some cases you may need to impose restrictions on the drag and drop behavior. For example you may want to disallow the dropping of a node to specific location, prevent node form being dropped at different level, or perhaps disable the auto expanding of the nodes while dragging.

WinForms RadTreeView Cancel a Drag and Drop Operation

Using AllowDrop property

You can interrupt a drag and drop operation by setting the AllowDrop property of a specific RadTreeNode to false. This way you still can drag this particular node, but you cannot add other nodes to it with drag and drop operation. You can set this for any particular node you want.


radTreeView1.Nodes[0].AllowDrop = false;

Restrict the user from changing the node hierarchy level with drag and drop

1. With the following code we will add some parent and child nodes to the tree view:

int count = 0;

for (int i = 0; i < 10; i++)
{
    RadTreeNode parentNode = new RadTreeNode("Parent Node" + i);              
    parentNode.AllowDrop = false;
    for (int j = 0; j < 3; j++)
    {
        RadTreeNode childNode = new RadTreeNode("Child Node" + count++);

        parentNode.Nodes.Add(childNode);
    }

    radTreeView1.Nodes.Add(parentNode);
}

2. Now we can subscribe to the DragEnding event and cancel the drop operation if the dragged node and target node have different hierarchy levels. Also we will show an appropriate message:


void radTreeView1_DragEnding(object sender, RadTreeViewDragCancelEventArgs e)
{
    if (e.TargetNode.Level != e.Node.Level)
    {
        e.Cancel = true;
        RadMessageBox.Show("Only nodes from the same level can be dropped here.");
    }
}

Cancel Auto Expansion for Dragged Nodes

The default behavior of RadTreeView when a node is dragged over a collapsed node is to automatically expand this node. To suppress this automatic expansion you can keep track of when a drag operation is in progress by using the DragStarted and DragEnded events. Then in the NodeExpandedChanging event handler we can cancel the expanding when drag and drop operation is in progress.


void radTreeView1_NodeExpandedChanging(object sender, RadTreeViewCancelEventArgs e)
{
    e.Cancel = radTreeView1.TreeViewElement.DragDropService.State == RadServiceState.Working;
}