Blue Theme Orange Theme Green Theme Red Theme
 
Click Here for 3 Month Free of ASP.NET Hosting!
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Windows Forms » Working with TreeView Control in C#

Working with TreeView Control in C#

This is an article addressing some of the basics of working with a TreeView control; the article will address dynamically adding TreeNodes to a TreeView control, searching the nodes to find and highlight a single node or a collection of nodes.

Author Rank:
Technologies: .NET 1.0/1.1, Common Controls, Controls, Windows Forms,Visual C# .NET
Total downloads : 4283
Total page views :  195116
Rating :
 4.9/5
This article has been rated :  10 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
TreeViewBasicsPack.zip
 
Become a Sponsor


Related EbooksTop Videos


Introduction

This is a short article addressing some of the basics of working with a TreeView control; the article will address dynamically adding TreeNodes to a TreeView control, searching the nodes to find and highlight a single node or a collection of nodes matching a search term against the TreeNode's tag, text, or name properties, and manually or programmatically selecting nodes.

Image1.jpg

Figure 1:  Searching a TreeView Control by the Text Property.

Image2.jpg

Figure 2:  Searching a TreeView Control by the Name Property.

Image3.jpg

Figure 3:  Searching a TreeView Control by the Name Property.

Image4.jpg

Figure 4:  Creating a Node with Specific Properties.

The Solution

The application solution contains a single Windows Application project comprised; all code supplied in support of this project is contained in two form classes; one is the main form containing the TreeView and a few controls used to display node information (Figures 1, 2, and 3) and to execute searches for a specific node or group of nodes based upon a user supplied search term.  The other form class (Figure 4) is used to create new nodes; within the application, this form is displayed by selecting a node from the TreeView and then selecting the "Add Node" option from the context menu.

There is nothing custom or fancy done with any of the TreeView related components in this application; it is merely a demonstration of how to work with a TreeView within the context of a Windows Forms application. 

The Code:  Form 1 - The Main Form

The main form class is a standard window form with a few controls added; the form contains a split container control; on the left hand side of the control is a TreeView controls, on the right hand side of the splitter are four group boxes; the first group box contains a set of labels and text boxes used to display information about a selected node, the remaining group boxes contain labels, text boxes, and buttons used to conduct different searches of the TreeView's node collection based on the node's text, name, or tag values.

The functionality contained in the class is broken up into several regions; the class begins with the default imports, namespace declaration, and class declaration: 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

namespace EasyTreeView

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

 

            // start off by adding a base treeview node

            TreeNode mainNode = new TreeNode();

            mainNode.Name = "mainNode";

            mainNode.Text = "Main";

            this.treeView1.Nodes.Add(mainNode);

        } 

 

The form class constructor creates a main node in the TreeView control; at runtime, the user may select this node (or any child node originating form this node) to add additional nodes to the TreeView. The form class also contains a context menu; this context menu contains two options; one to add a new node, and one to delete an existing node. When a new node is requested, the application opens an instance of the New Node dialog; this dialog forces the user to set the name, text, and tag values for the new node. The tag value can be any object but in this example, the tag is limited to holding an additional string value. Once the values have been collected from the dialog, the new node is populated with the information and added to the selected node of the TreeView.

 

When a node is deleted, the selected node and all of its children are removed from the TreeView; one thing to note here is, if you are associating an object with a node through its tag; you will want to write the handler to destroy that object prior to deleting the selected node. 

 

#region Add and Remove Nodes

 

/// <summary>

/// Add a Treeview node using a dialog box

/// forcing the user to set the name and text properties

/// of the node

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void cmnuAddNode_Click(object sender, EventArgs e)

{

    NewNode n = new NewNode();

    n.ShowDialog();

    TreeNode nod = new TreeNode();

    nod.Name = n.NewNodeName.ToString();

    nod.Text = n.NewNodeText.ToString();

    nod.Tag = n.NewNodeTag.ToString();

    n.Close();

 

    treeView1.SelectedNode.Nodes.Add(nod);

    treeView1.SelectedNode.ExpandAll();

} 

 

/// <summary>

/// Remove the selected node and it children

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void cmnuRemoveNode_Click(object sender, EventArgs e)

{

    treeView1.SelectedNode.Remove();

} 

       

#endregion 

 

The next region of code is used to handle TreeView events; there are only two events handled in this section; the TreeView's After Select event and the TreeView's click event. The After Select event handler is used to populate the text boxes used to display information from the selected node (its Name, Text, Tag, and Parent text properties. The find functions described later highlight all found nodes in response to a search by setting the background color of each matching node to Yellow; the click event handler for the TreeView is used to remove all such highlighting. 

      

#region Treeview Event Handlers

 

/// <summary>

/// Display information about the selected node

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void treeView1_AfterSelect(object sender, TreeViewEventArgs  e)

{

    try

    {

        txtName.Text = "";

        txtParentName.Text = "";

        txtText.Text = "";

        txtTag.Text = "";

 

        txtName.Text = treeView1.SelectedNode.Name.ToString();

        txtText.Text = treeView1.SelectedNode.Text.ToString();

        txtTag.Text = treeView1.SelectedNode.Tag.ToString();

        txtParentName.Text = treeView1.SelectedNode.Parent.Text.ToString();

    }

    catch { }

} 

 

/// <summary>

/// Clear nodes marked by the find functions

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void treeView1_Click(object sender, EventArgs e)

{

    ClearBackColor();

}

 

#endregion 

 

The next region in the class is used to find a node by its name property. The method of finding a node by its name is the only find function directly supported by the TreeView; if you want to find a node by something other than its name, you will have to write your own methods to do so. This click event handler populates an array of nodes with an array of nodes with matching names. The find method accepts to arguments; the first argument is the search term and the second is a Boolean value used to determine whether or not child nodes should also be included in the search; in this case the search term is collected from a text box on the form and the option of searching child nodes is enabled by setting the second argument to true. 

 

Once the collection of nodes is created; each matching node has its back color set to yellow so as to highlight the node in the TreeView. Prior to setting the back color of the matching nodes, all of the other nodes in the TreeView are set back to having white backgrounds by calling the Clear Back Color method. 

       

#region Find By Name

 

/// <summary>

/// Use the treeview's built-in find function

/// to search for a node

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void btnFindNode_Click(object sender, EventArgs e)

{

    ClearBackColor(); 

    try

    {

        TreeNode[] tn = treeView1.Nodes[0].Nodes.Find(txtNodeSearch.Text, true);

        for (int i = 0; i < tn.Length; i++)

        {

            treeView1.SelectedNode = tn[i];

            treeView1.SelectedNode.BackColor = Color.Yellow;

        }

    }

    catch { }

}

 

#endregion 

 

The next region of code is used to remove the back color from any nodes highlighting in an earlier search. This process relies on two separate methods. The first method creates an instance of a tree node collection containing all of the nodes in the form's TreeView control. Each of the nodes in the collection is passed to a second method (Clear Recursive); this second method is passed the current node. The Clear Recursive method loops through all of the nodes contained within the passed in nodes node collection and sets the back color of each of those nodes to the color white. Each node is then passed recursively back to the same Clear Recursive method where each node's node collection is processed until there are not more nodes remaining to process. In this way, each node and child node in the entire tree is processed.

 

While this process is used merely to set each node's back color to white, the same approach may be used whenever the entire tree must be processed; in fact, the remaining search methods will do just that. 

       

#region Remove BackColor

 

// recursively move through the treeview nodes

// and reset backcolors to white

private void ClearBackColor()

{

    TreeNodeCollection nodes = treeView1.Nodes;

    foreach (TreeNode n in nodes)

    {

        ClearRecursive(n);

    }

}

 

// called by ClearBackColor function

private void ClearRecursive(TreeNode treeNode)

{

    foreach (TreeNode tn in treeNode.Nodes)

    {

        tn.BackColor = Color.White;

        ClearRecursive(tn);

    }

}

       

#endregion 

 

The next region of code is used to find a node or nodes with text properties matching a search expression. The form contains a group box used to set a text search term and evoke the method from a button click event handler. The button click first clears all highlighted nodes by calling the Clear Back Color method; after the nodes are all restored to white backgrounds, the handler calls the Find By Text method; this method works much like the method described for clearing the back color. The method assembles a collection of the tree view nodes and then passes each node to the recursive method. The find recursive method looks for nodes with text properties matching the search expression and, when a match is found, sets the back color to yellow.  Each processed node is passed back to the find recursive method which will continue to examine each node until all of the nodes in the tree have been evaluated. 

       

#region Find By Text

 

/// <summary>

/// Searching for nodes by text requires a special function

/// this function recursively scans the treeview and

/// marks matching items.

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void btnNodeTextSearch_Click(object sender, EventArgs e)

{

    ClearBackColor();

    FindByText();

} 

 

private void FindByText()

{

    TreeNodeCollection nodes = treeView1.Nodes;

    foreach (TreeNode n in nodes)

    {

        FindRecursive(n);

    }

} 

 

private void FindRecursive(TreeNode treeNode)

{

    foreach (TreeNode tn in treeNode.Nodes)

    {

        // if the text properties match, color the item

        if (tn.Text == this.txtNodeTextSearch.Text)

            tn.BackColor = Color.Yellow;

 

        FindRecursive(tn);

    }

}

       

#endregion 

 

The next region is used to contain the methods used to find nodes by their tag value (which in this case is a string); and to highlight in yellow any matching nodes. These methods work much like the last method with the exception that the matches are determined by their tag values rather than their text values. 

 

#region Find By Tag

 

/// <summary>

/// Searching for nodes by tag requires a special function

/// this function recursively scans the treeview and

/// marks matching items.  Tags can be object; in this

/// case they are just used to contain strings

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void btnNodeTagSearch_Click(object sender, EventArgs e)

{

    ClearBackColor();

    FindByTag();

}

 

private void FindByTag()

{

    TreeNodeCollection nodes = treeView1.Nodes;

    foreach (TreeNode n in nodes)

    {

        FindRecursiveTag(n);

    }

} 

 

private void FindRecursiveTag(TreeNode treeNode)

{

    foreach (TreeNode tn in treeNode.Nodes)

    {

        // if the text properties match, color the item

        if (tn.Tag.ToString() == this.txtTagSearch.Text)

            tn.BackColor = Color.Yellow;

 

        FindRecursiveTag(tn);

    }

} 

       

#endregion 


That wraps up all of the code necessary to add and remove nodes, and to search for specific nodes based upon their name, text, or tag values.
 

The Code:  Form 2 - New Node Form

The code supplied in the New Node form is used merely to capture the user supplied values used to populate a newly created node's name, text, and tag properties. The form is displayed as a dialog and appears in response to the user requesting the addition of a new node from the main form of the application. The imports, namespace declaration, and class declaration are all in the default configuration for a form class:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

namespace EasyTreeView

{

    public partial class NewNode : Form

    { 

       

Following the class declaration, three local member variables are defined; each of which is used to store the user supplied name, text, and tag properties: 

 

#region Local Variables

 

private string mNewNodeName;

private string mNewNodeText;

private string mNewNodeTag; 

 

#endregion 

 

The form constructor is in the default configuration: 

 

/// <summary>

/// Default constructor

/// </summary>

public NewNode()

{

    InitializeComponent();

} 

 

The next region of code is used to define three public properties used to hold the new node name, text, and tag values. Once the user has set these values on this form, the main form collects these properties and assigns them to the new node's name, text, and tag properties. 

 

#region Class Properties

 

public string NewNodeName

{

    get

    {

        return mNewNodeName;

    }

    set

    {

        mNewNodeName = value;

    }

}

 

public string NewNodeText

{

    get

    {

        return mNewNodeText;

    }

    set

    {

        mNewNodeText = value;

    }

} 

 

public string NewNodeTag

{

    get

    {

        return mNewNodeTag;

    }

    set

    {

        mNewNodeTag = value;

    }

} 

       

#endregion 

 

This button click event handler is intended to force the user to set all three values; once each is set, the related properties are passed the correct values and the form is closed. 

 

private void btnSubmit_Click(object sender, EventArgs e)

{ 

    if (txtNewNodeName.Text != string.Empty)

    {

        NewNodeName = txtNewNodeName.Text;

    }

    else

    {

        MessageBox.Show("Name the node.");

        return;

    }

 

    if (txtNewNodeText.Text != string.Empty)

    {

        NewNodeText = txtNewNodeText.Text;

    }

    else

    {

        MessageBox.Show("Provide the new node's text");

        return;

    }

 

    if (txtTag.Text != string.Empty)

    {

        NewNodeTag = txtTag.Text;

    }

    else

    {

        MessageBox.Show("Provide the new node's text");

        return;

    } 

    this.Close();

}  

  

That is all there is to it. Once this code is executed, may right click on the main node and add as many nodes and child nodes as they see fit. The user may enter in valid search expression into any of the search optons and highlight matching nodes, or the user may select nodes from the tree and read the associated name, text, tag and parent values from the selected node. 

Summary.

Naturally there are countless ways to use the TreeView control and this simple demonstration does not begin to explore the variety of options available. The sole intent of the demonstration was to provide a description of how one might add and remove nodes, obtain information from selected nodes, and search for specific nodes on the basis of the node's name, text, and tag values.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
TreeViewBasicsPack.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor
 Comments
Question by venkat On February 26, 2009
How to perform a different operation for each selected node
Reply | Email | Delete | Modify | 
Re: Question by Scott On March 1, 2009
I'm not sure what you need to do but if you need to handle the nodes differently you can put something in the tag property that will tell you how to handle a click event or something; or you could extend the node and add additional properties to that will tell you what you need to know in response to the event you are handling.
Reply | Email | Delete | Modify | 
saving my nods by khaled On May 29, 2009
many thanks about this example
but how I can save the nodes after I add it, I notice it's gone after colseing  program
need help
thanks
Reply | Email | Delete | Modify | 
tree view functionality in datagrid by ashish On July 29, 2009
hi ,
        I want tree view functionality in datagrid. means when i click on and node its child node gets visible in grid row .....
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved