How to Search and Drag-Drop Nodes in a TreeView Control

Posted by: Suprotim Agarwal , on 9/15/2008, in Category WinForms & WinRT
Views: 68170
Abstract: In this article, we will explore how to drag and drop nodes in a Treeview control. We will also explore how to search nodes in a TreeView.
How to Search and Drag-Drop Nodes in a TreeView Control
 
One of our dotnetcurry.com viewers Tim-Ann, asked me two queries about the TreeView control. He wanted to search a node and then move that node within the TreeView control. I thought of dedicating an article on it.
In this article, we will explore how to drag and drop nodes in a Treeview control. We will also explore how to search nodes in a TreeView.
Step 1: Create a Windows Forms Application. Drag and drop a Button(btnSearch) and a TextBox(txtSearch) on to the form.  Now add a TreeView(tvw) control to the form.
In the Form_Load() add the following code to populate the TreeView:
C#
private void Form1_Load(object sender, EventArgs e)
{
    treeView1.BeginUpdate();
    treeView1.Nodes.Add(".NET");
    treeView1.Nodes[0].Nodes.Add("Programming");
    treeView1.Nodes[0].Nodes[0].Nodes.Add("C#");
    treeView1.Nodes[0].Nodes[0].Nodes.Add("VB.NET");
    treeView1.Nodes.Add("Servers");
    treeView1.Nodes[1].Nodes.Add("Windows Server");
    treeView1.Nodes[1].Nodes[0].Nodes.Add("W2K3");
    treeView1.Nodes[1].Nodes[0].Nodes.Add("W2K8");
    treeView1.Nodes[1].Nodes.Add("SQL Server 2008");
    treeView1.Nodes[1].Nodes.Add("Exchange Server");
    // Expand all tree nodes when first loaded
    treeView1.ExpandAll();
    treeView1.EndUpdate();
    treeView1.AllowDrop = true;
}
VB.NET
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
      treeView1.BeginUpdate()
      treeView1.Nodes.Add(".NET")
      treeView1.Nodes(0).Nodes.Add("Programming")
      treeView1.Nodes(0).Nodes(0).Nodes.Add("C#")
      treeView1.Nodes(0).Nodes(0).Nodes.Add("VB.NET")
      treeView1.Nodes.Add("Servers")
      treeView1.Nodes(1).Nodes.Add("Windows Server")
      treeView1.Nodes(1).Nodes(0).Nodes.Add("W2K3")
      treeView1.Nodes(1).Nodes(0).Nodes.Add("W2K8")
      treeView1.Nodes(1).Nodes.Add("SQL Server 2008")
      treeView1.Nodes(1).Nodes.Add("Exchange Server")
      ' Expand all tree nodes when first loaded
      treeView1.ExpandAll()
      treeView1.EndUpdate()
      treeView1.AllowDrop = True
End Sub
Step 2: We will first create the functionality to ‘Search’ a TreeView. On the btnSearch click event, add the following code:
C#
private void FindInTreeView(TreeNodeCollection tncoll, string strNode)
{
    foreach (TreeNode tnode in tncoll)
    {
        if (tnode.Text.ToLower() == strNode.ToLower())
        {
            tnode.ForeColor = Color.Blue;
            tnode.TreeView.SelectedNode = tnode;
        }
        else
        {
            tnode.BackColor = tnode.TreeView.BackColor;
        }
        FindInTreeView(tnode.Nodes, strNode);
    }
}
 
VB.NET
Private Sub FindInTreeView(ByVal tncoll As TreeNodeCollection, ByVal strNode As String)
      For Each tnode As TreeNode In tncoll
            If tnode.Text.ToLower() = strNode.ToLower() Then
                  tnode.ForeColor = Color.Blue
                  tnode.TreeView.SelectedNode = tnode
            Else
                  tnode.BackColor = tnode.TreeView.BackColor
            End If
            FindInTreeView(tnode.Nodes, strNode)
      Next tnode
End Sub
 
The code above searches the nodes recursively. Using a ForEach loop, we traverse the nodes and then compare the search item with the treenode text. If it matches, we highlight the node with a different color.
Step 3: Let us now add functionality to drag and drop nodes in the TreeView. We would first need to register a few events as shown below:
C#
private void RegisterEvents()
{
    this.tvw.DragDrop += new System.Windows.Forms.DragEventHandler(this.tvw_DragDrop);
    this.tvw.DragEnter += new System.Windows.Forms.DragEventHandler(this.tvw_DragEnter);
    this.tvw.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.tvw_ItemDrag);
}
VB.NET
Private Sub RegisterEvents()
      AddHandler tvw.DragDrop, AddressOf tvw_DragDrop
      AddHandler tvw.DragEnter, AddressOf tvw_DragEnter
      AddHandler tvw.ItemDrag, AddressOf tvw_ItemDrag
End Sub
Note: Call the RegisterEvents() in your Form_Load.
The next step is to add functionality to these event handlers :
C#
private void tvw_ItemDrag(object sender, ItemDragEventArgs e)
{
    tvw.DoDragDrop(e.Item, DragDropEffects.Move);
}
 
private void tvw_DragEnter(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.Move;
}
 
private void tvw_DragDrop(object sender, DragEventArgs e)
{
    Point loc = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
    TreeNode node = (TreeNode)e.Data.GetData(typeof(TreeNode));
    TreeNode destNode = ((TreeView)sender).GetNodeAt(loc);
 
    if (node.Parent == null)
        node.TreeView.Nodes.Remove(node);
    else
        node.Parent.Nodes.Remove(node);
 
    if (destNode.Parent == null)
        destNode.TreeView.Nodes.Insert(destNode.Index + 1, node);
    else
        destNode.Parent.Nodes.Insert(destNode.Index + 1, node);
}
VB.NET
Private Sub tvw_ItemDrag(ByVal sender As Object, ByVal e As ItemDragEventArgs)
      tvw.DoDragDrop(e.Item, DragDropEffects.Move)
End Sub
 
Private Sub tvw_DragEnter(ByVal sender As Object, ByVal e As DragEventArgs)
      e.Effect = DragDropEffects.Move
End Sub
 
Private Sub tvw_DragDrop(ByVal sender As Object, ByVal e As DragEventArgs)
      Dim loc As Point = (CType(sender, TreeView)).PointToClient(New Point(e.X, e.Y))
      Dim node As TreeNode = CType(e.Data.GetData(GetType(TreeNode)), TreeNode)
      Dim destNode As TreeNode = (CType(sender, TreeView)).GetNodeAt(loc)
 
      If node.Parent Is Nothing Then
            node.TreeView.Nodes.Remove(node)
      Else
            node.Parent.Nodes.Remove(node)
      End If
 
      If destNode.Parent Is Nothing Then
            destNode.TreeView.Nodes.Insert(destNode.Index + 1, node)
      Else
            destNode.Parent.Nodes.Insert(destNode.Index + 1, node)
      End If
End Sub
As shown in the code above, the ItemDrag event is raised from the TreeView control as soon as the user starts to drag the tree node. The DoDragDrop method initiates the drag-and-drop procedure.
The DragEnter event occurs when the TreeNode object is dragged from one point of the TreeView control to another point within the TreeView control. In this event, you can check the validity of the drag operation.
Finally the DragDrop event occurs when the TreeNode object is dropped at the destination point of the TreeView control. The drop point is calculated and the TreeNode object is retrieved, that is to be added to the destination node. That is all the code that is needed to initiate a drag and drop. Just make sure that the ‘AllowDrop’ property on the TreeView is set to True.
In this article, we explored how to search nodes in a TreeView control. We also explored how to drag and drop nodes in a treeview control. I hope this article was useful and I thank you for viewing it. 
If you liked the article,  Subscribe to my RSS Feed.
Give me a +1 if you think it was a good article. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal




Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by sasi on Monday, October 06, 2008 6:18 AM
some what needed
Comment posted by Gabor Kovacs on Wednesday, February 11, 2009 9:51 AM
Bug in this code, if you select tree node and move to selves then selected node is deleted.

Fix in c# code:

  TreeNode destNode = ((TreeView)sender).GetNodeAt(loc);

+ if (node == destNode) return;

  if (node.Parent == null)
Comment posted by chaman gonzalves on Friday, March 20, 2009 5:51 PM
private TreeNode findNodeInTree(TreeNodeCollection coll, string nodeText)
        {
            int nodeCount = 0;
            TreeNode retNode = null;
            foreach (TreeNode nd in coll)
            {
                if (nd.Text == nodeText)
                {
                    retNode = nd;
                    break;
                }
                else
                {
                    nodeCount++;
                }
                if(nodeCount == coll.Count)
                    findNodeInTree(nd.Nodes, nodeText);
            }            
            return retNode;
Comment posted by chaman gonzalves on Monday, March 23, 2009 9:20 AM
private TreeNode findNodeInTree(TreeNodeCollection coll, string nodeText)
        {
            int nodeCount = 0;
            TreeNode retNode = null;
            foreach (TreeNode nd in coll)
            {
                if (nd.Text == nodeText)
                {
                    retNode = nd;
                    break;
                }
                else
                {
                    nodeCount++;
                }
                if(nodeCount == coll.Count)
                    findNodeInTree(nd.Nodes, nodeText);
            }            
            return retNode;
Comment posted by mahi@swetha1 on Thursday, July 02, 2009 8:44 AM
My friends,
how to implement expandable and collapsible properties for usercontrol?
I request u to help me in sorting out a solution for a usercontrol made up of two panels.I like to implement expandable and collapsable features to usercontrol.So that the child controls or usercontrols placed below it should shift upwards and downwards.
In the same usercontrol,How can i proceed if i like to resize the usercontrol at design time as well as runtime?


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
  
namespace Freshm
{
[Designer(typeof(Freshm1))]
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private void UserControl1_Load(object sender, EventArgs e)
{
button1.Visible = false;
button2.Visible = true;
panel2.Visible = true;
//if (button2.Visible == true)
//{
// this.Height = 52;
// this.Width = 150;
//}
}
#region button_click events
private void button2_Click(object sender, EventArgs e)
{
button2.Visible = false;
button1.Visible = true;
panel2.Visible = false;
if (button2.Visible == false)
{
this.Height = 52;
this.Width = 150;
panel1.Height = this.Height;
panel1.Width = this.Width;
}
}
private void button1_Click(object sender, EventArgs e)
{
button1.Visible = false;
button2.Visible = true;
panel2.Visible = true;
if (button2.Visible == true)
{
this.Height = 146;
this.Width = 150;
panel1.Height = this.Height;
panel1.Width = this.Width;
}
}
#endregion

#region Serialization
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Panel ControlPanel
{
get
{
return this.panel1;
}

}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Panel ControlPanel2
{
get
{
return this.panel2;
}
}
#endregion
#region Properties
public string DisplayText
{
get
{
return this.label1.Text;
}
set
{
label1.Text = value;
}
}
public System.Drawing.Font TextFont
{
get
{
return this.label1.Font;
}
set
{
label1.Font = value;
}
}
public System.Drawing.Color pnl1TextColor
{
get
{
return this.panel1.BackColor;
}
set
{
panel1.BackColor = value;
}
}
public Color pnl2TextColor
{
get
{
return this.panel2.BackColor;
}
set
{
panel2.BackColor = value;
}
}
public Color UCTextColor
{
get
{
return this.BackColor;
}
set
{
this.BackColor = value;
}
}
public Size UCTextsize
{
get
{
return this.Size;
}
set
{
this.Size = value;
}
}
#endregion
//private void button1_Click(Object sender,System.EventArgs e)
//{

//}
//#region Fields
//private ToggleButton btnExpandOrCollapse;
//private FrameworkElement contentElement;
//private VisualState collapsedState;
//#endregion
//public bool IsExpanded
//{
// get { return (bool)GetValue(IsExpandedProperty); }
// set
// {
// SetValue(IsExpandedProperty, value);
// if (btnExpandOrCollapse != null)
// btnExpandOrCollapse.IsChecked = IsExpanded;
// }
//}
  
}
}
  
  
  
  
  
  
  
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms.Design;
namespace Freshm
{
public class Freshm1 : ParentControlDesigner
{
public override void Initialize(System.ComponentModel.IComponent component)
{
base.Initialize(component);
if (this.Control is UserControl1)
{
this.EnableDesignMode(((UserControl1)this.Control).ControlPanel, "ControlPanel");
this.EnableDesignMode(((UserControl1)this.Control).ControlPanel2, "ControlPanel2");
}
}
}
}
  
  
  
  
  
namespace Freshm
{
partial class UserControl1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.panel1 = new System.Windows.Forms.Panel();
this.label1 = new System.Windows.Forms.Label();
this.button2 = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.panel2 = new System.Windows.Forms.Panel();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.BackColor = System.Drawing.SystemColors.AppWorkspace;
this.panel1.Controls.Add(this.label1);
this.panel1.Controls.Add(this.button2);
this.panel1.Controls.Add(this.button1);
this.panel1.Location = new System.Drawing.Point(0, 3);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(150, 52);
this.panel1.TabIndex = 0;
//
// label1
//
this.label1.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
this.label1.Font = new System.Drawing.Font("Times New Roman", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.label1.Location = new System.Drawing.Point(31, 10);
this.label1.Margin = new System.Windows.Forms.Padding(3);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(96, 14);
this.label1.TabIndex = 2;
this.label1.Text = "Enter Ur Name";
//
// button2
//
this.button2.Image = global::Freshm.Properties.Resources.NORMALGROUPCOLLAPSE;
this.button2.Location = new System.Drawing.Point(3, 3);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(22, 23);
this.button2.TabIndex = 1;
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button1
//
this.button1.Image = global::Freshm.Properties.Resources.NORMALGROUPEXPAND;
this.button1.Location = new System.Drawing.Point(3, 3);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(22, 23);
this.button1.TabIndex = 0;
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// panel2
//
this.panel2.BackColor = System.Drawing.SystemColors.ButtonShadow;
this.panel2.Location = new System.Drawing.Point(0, 53);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(150, 94);
this.panel2.TabIndex = 1;
//
// UserControl1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.Location = new System.Drawing.Point(0, -2);
this.Name = "UserControl1";
this.Size = new System.Drawing.Size(150, 145);
this.Load += new System.EventHandler(this.UserControl1_Load);
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Panel panel2;
}
}



      

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel