New to Telerik UI for ASP.NET AJAXStart a free 30-day trial

Switching source and destination nodes and moving their children in RadTreeView

How to

Switch the source and destination nodes and their children in the treeview (using the drag and drop mechanism).

Solution

Custom modification of the NodeDrop event handler of RadTreeView will do the job. Review the following code snippets:

C#
protected void RadTreeView1_NodeDrop(object sender, Telerik.Web.UI.RadTreeNodeDragDropEventArgs e)
{
    RadTreeNode sourceNode = e.SourceDragNode;
    RadTreeNode destNode = e.DestDragNode;

    if (((sourceNode.Parent != null) && (sourceNode.Parent.Equals(destNode))) ||
        ((destNode.Parent != null) && (destNode.Parent.Equals(sourceNode))))
    {
        return;
    }

    string text = sourceNode.Text;
    string category = sourceNode.Category;
    string node_value = sourceNode.Value;

    ArrayList sourceNodeChildren = new ArrayList();
    ArrayList destNodeChildren = new ArrayList();

    foreach (RadTreeNode childNode in sourceNode.Nodes)
    {
        sourceNodeChildren.Add(childNode);
    }

    foreach (RadTreeNode childNode in destNode.Nodes)
    {
        destNodeChildren.Add(childNode);
    }

    sourceNode.Text = destNode.Text;
    sourceNode.Category = destNode.Category;
    sourceNode.Value = destNode.Value;

    sourceNode.Nodes.Clear();

    foreach (RadTreeNode childNode in destNodeChildren)
    {
        sourceNode.Nodes.Add(childNode);
    }

    destNode.Text = text;
    destNode.Category = category;
    destNode.Value = node_value;

    destNode.Nodes.Clear();

    foreach (RadTreeNode childNode in sourceNodeChildren)
    {
        destNode.Nodes.Add(childNode);
    }

    sourceNode.Expanded = true;
    destNode.Expanded = true;
}

Keep in mind that this will save only the Text, Category and Value attributes of the exchanged nodes. Info of other kind will be lost. If you would like to keep other additional properties and functions connected to the corresponding nodes, you should add extra code in the HandleDrop event handler.

In this article
How toSolution
Not finding the help you need?
Contact Support