Home

View-Based Controls

 

The Tree View

 

Introduction

A tree view is a control that resembles an upside down tree and displays a hierarchical list of items. Like a normal tree, a tree view starts in the top section with an object referred to as the root. Under the root, a real tree is made of branches and leaves. In an application, a tree view is only made of branches and each branch is called a node. In real world, a leaf cannot have a branch as its child, only a branch can have another branch as its child and a branch can have a leaf as a child. In an application, a node (any node) can have a node as a child.

Like a real world tree, the branches or nodes of a tree view use a type of relationship so that they are not completely independent. For example, a tree view can be based on a list that has a parent item and other child items that depend on that parent. In real world, if you cut a branch, the branches and leaves attached to it also disappear. This scenario is also valid for a tree view.

Most of the time, a tree has only one root but a tree in an application can have more than one root.

 
 

Tree View Creation

In a Windows application a tree view is primarily a control like any other. To use it in your application, you can click the TreeView button in the Toolbox and click a form or other control in your application. This is programmatically equivalent to declaring a pointer to TreeView, using the new operator to instantiate it and adding it to its container's list of controls through a call to the Controls.Add() method. Here is an example:
private void btnCreate_Click(object sender, System.EventArgs e)
{
	TreeView tvwCountries = new TreeView();
	tvwCountries.Location  = new Point(10, 50);
	tvwCountries.Width      = 220;
	tvwCountries.Height     = 260;

	Controls.Add(tvwCountries);
}

Using a TreeView variable only adds a rectangular empty control to your application. The next action you probably take is to add one or more branches to the tree.

Practical LearningPractical Learning: Introducing the Tree View Control

  1. Start a new Windows Forms Application named DeptStore1
  2. Change the form's Text to Department Store
  3. In the Windows Forms section of the Toolbox, click TreeView and click the form
  4. Using the Properties window, change its properties as follows:
    (Name): tvwStoreItems
    Anchor: Top, Bottom, Left, Right
  5. Add a Button to the form and change its properties as follows:
    (Name): btnClose
    Text: Close
    Anchor: Bottom, Right

     
  6. Double-click the Close button and implement its Click event as follows:
     
    private void btnClose_Click(object sender, System.EventArgs e)
    {
    	Close();
    }
  7. Save all
 

Operations on Tree View's Nodes

 

Introduction to Creating Nodes

To create the nodes of a tree view, Microsoft Visual Studio .NET provides a convenient dialog box you can use at design time. To display it, after adding a TreeView control to a form, you can click the ellipsis button of its Nodes field in the Properties window. This causes the TreeNode Editor to display:

TreeNode Editor

Probably the primary characteristic of a node is the text it displays.

At design time and in the TreeNode Editor, to add a branch, you can click the Add Root button. When you do this, a node with a default but incremental name is created. To edit a node's name, first select it in the Select Node To Edit list, then, in the Label text box, change the string as you wish.

The branches of a tree view are stored in a property called Nodes. The Nodes property is an object based on the TreeNodeCollection class. As its name indicates, the Nodes property carries all of the branches of a tree view. This means that the Nodes property in fact represents a collection. Each member of this collection is called a node and it is an object based on the TreeNode class.

At run time, to create a new node, call the TreeNodeCollection.Add() method which is overloaded with two versions. One of the versions of this method uses the following syntax:

public virtual TreeNode Add(string text);

This method takes as argument the string that the branch will display. This method is also the prime candidate to create a root node. Here is an example of calling it:
private void btnCreate_Click(object sender, System.EventArgs e)
{
	TreeView tvwCountries = new TreeView();
	tvwCountries.Location  = new Point(10, 50);
	tvwCountries.Width      = 220;
	tvwCountries.Height     = 260;

	Controls.Add(tvwCountries);

	tvwCountries.Nodes.Add("World");
}

The other version of the TreeNodeCollection.Add() method uses the following syntax:

public virtual int Add(TreeNode node);

This method takes as argument a TreeNode object. In other words, it expects a complete or semi-complete branch already defined elsewhere.

The TreeNode class is equipped with various constructors you can use to instantiate it. Its default constructor allows you to create a node without primarily giving its details. Another TreeNode constructor has the following syntax:

public TreeNode(string text);

This constructor takes as argument the string that the node will display. Here is an example of using it and adding its newly create node to the tree view:

private void btnCreate_Click(object sender, System.EventArgs e)
{
	TreeView tvwCountries = new TreeView();
	tvwCountries.Location  = new Point(10, 50);
	tvwCountries.Width      = 220;
	tvwCountries.Height     = 260;

	Controls.Add(tvwCountries);

	TreeNode nodElement = new TreeNode("World");
	tvwCountries.Nodes.Add(nodElement);
}

We mentioned that the primary characteristic of a node is the text it displays. The text of a node is stored in a property of the TreeNode class and is called Text. This allows you either to specify the string of a node or to retrieve it when needed. Here is an example of setting it:

private void btnCreate_Click(object sender, System.EventArgs e)
{
	TreeView tvwCountries = new TreeView();
	tvwCountries.Location  = new Point(10, 50);
	tvwCountries.Width      = 220;
	tvwCountries.Height     = 260;

	Controls.Add(tvwCountries);

	TreeNode nodElement = new TreeNode();
	nodElement.Text = "World";
	tvwCountries.Nodes.Add(nodElement);
}

Just as we called the TreeNodeCollection.Add() method to create a branch, you can call it as many times as necessary to create additional branches. Here is an example:
private void btnCreate_Click(object sender, System.EventArgs e)
{
	TreeView tvwCountries = new TreeView();
	tvwCountries.Location = new Point(10, 50);
	tvwCountries.Width = 220;

	Controls.Add(tvwCountries);

	tvwCountries.Nodes.Add("World");
	tvwCountries.Nodes.Add("Jupiter");
	tvwCountries.Nodes.Add("Neptune");
	tvwCountries.Nodes.Add("Uranu");
}

Alternatively, if you have many branches to add to the tree, you can first create them as an array of TreeNode values, then called the TreeNodeCollection.AddRange() method. The syntax of this method is:

public virtual void AddRange(TreeNode[] nodes);

This method takes as argument an array of TreeNode objects. Here is an example:

private void btnCreate_Click(object sender, System.EventArgs e)
{
	 TreeView tvwCountries = new TreeView();
	 tvwCountries.Location = new Point(10, 50);
	 tvwCountries.Width = 220;
	 Controls.Add(tvwCountries);

	 TreeNode[] nodPlanets = { new TreeNode("World"), new TreeNode("Jupiter"),
				 new TreeNode("Neptune"), new TreeNode("Uranu") };
	 tvwCountries.Nodes.AddRange(nodPlanets);
}

 

Practical LearningPractical Learning: Creating the Root Node

  1. On the form, double-click an unoccupied area of its body to access its Load event
  2. To create the first node of the tree, implement the event as follows:
     
    private void Form1_Load(object sender, System.EventArgs e)
    {
    	TreeNode nodDeptStore = new TreeNode("Store Item");
    
    	this.tvwStoreItems.Nodes.Add(nodDeptStore);
    }
  3. Execute the application to test the form
     
  4. Close the form and return to your programming environment

Creating Child Nodes

At design time and in the TreeNode Editor, to create a child node for an existing item, first select it in the Select Node To Edit list, then click the Add Child button. This causes a child node to be created for the selected item. To edit its name, first click it and change the string in the Label text box.

At run time, to create a child node, first get a reference to the node that will be used as its parent. One way you can get this reference is to obtain the returned value of the first version of the TreeNodeCollection.Add() method. As its syntax indicates, this method returns a TreeNode object.

We have used the default constructor of the TreeNode class and the constructor that takes as argument a string. The TreeNode class provides another constructor whose syntax is:

public TreeNode(string text, TreeNode[] children);

The first argument of this method is the string that the new node this constructor creates will display. The second argument is a collection of the child nodes of this branch. The collection is passed as an array. Based on this, you use this constructor to create a new node including its children. After creating the new node, you can pass it to the TreeNodeCollection.Add() method as we did earlier. Here is an example:
private void btnCreate_Click(object sender, System.EventArgs e)
{
	 TreeView tvwCountries = new TreeView();
	 tvwCountries.Location = new Point(10, 50);
	 tvwCountries.Width = 220;

	 Controls.Add(tvwCountries);

	 TreeNode[] nodContinents = { new TreeNode("Africa"),
				   new TreeNode("America"),
				   new TreeNode("Asia"),
				   new TreeNode("Europe") };

	 TreeNode nodWorld = new TreeNode("World", nodContinents);
	 tvwCountries.Nodes.Add(nodWorld);
}

Using the same approach, you can create as many branches and their child nodes as you wish. Here is an example:
private void btnCreate_Click(object sender, System.EventArgs e)
{
	 TreeView tvwCountries = new TreeView();
	 tvwCountries.Location = new Point(10, 50);
	 tvwCountries.Width = 220;
	 tvwCountries.Height = 260;

	 Controls.Add(tvwCountries);

	 // Create a list of some African countries and 
	 // store them in an array named nodAfricans
	 TreeNode[] nodAfricans = { new TreeNode("Senegal"),
		                               new TreeNode("Botswana"),
			               new TreeNode("Ghana"),
			               new TreeNode("Morocco") };

	 // Create a list of some American countries and 
	 // store them in an array named nodAmericans
	 TreeNode[] nodAmericans = { new TreeNode("Canada"),
		                                   new TreeNode("Jamaica"),
				   new TreeNode("Colombia")};

	 // Create a list of some European countries and 
	 // store them in an array named nodEuropeans
	 TreeNode[] nodEuropeans = { new TreeNode("Italy"),
		                                    new TreeNode("Greece"),
				    new TreeNode("Spain"),
				    new TreeNode("England") };

	 // Create a list of continents, independently
	 TreeNode nodAfrica  = new TreeNode("Africa", nodAfricans);
	 TreeNode nodAmerica = new TreeNode("America", nodAmericans);
	 TreeNode nodAsica   = new TreeNode("Asia");
	 TreeNode nodEurope  = new TreeNode("Europe", nodEuropeans);

	 // Store the list of continents in an array named nodContinents
	 TreeNode[] nodContinents = { nodAfrica, nodAmerica, nodAsica, nodEurope };

	 // Create a branch named nodWorld and store the list of
	 // continents as its child
	 TreeNode nodWorld = new TreeNode("World", nodContinents);

	 // Finally, add the nodWorld branch to the tree view
	 tvwCountries.Nodes.Add(nodWorld);
}

The number of nodes in the TreeNode objects is stored in the TreeNodeCollection.Count property. To get the current number of nodes in the tree view, you can call the TreeView.GetNodeCount() method. Its syntax is:

public int GetNodeCount(bool includeSubTrees);

Here is an example:

private void btnCreate_Click(object sender, System.EventArgs e)
{
	 TreeView tvwCountries = new TreeView();
	 tvwCountries.Location = new Point(10, 50);
	 tvwCountries.Width = 220;
	 tvwCountries.Height = 260;

	 Controls.Add(tvwCountries);

	 // Create a list of some African countries and 
	 // store them in an array named nodAfricans
	 TreeNode[] nodAfricans = { new TreeNode("Senegal"),
		                               new TreeNode("Botswana"),
			               new TreeNode("Ghana"),
			               new TreeNode("Morocco") };

	 // Create a list of some American countries and 
	 // store them in an array named nodAmericans
	 TreeNode[] nodAmericans = { new TreeNode("Canada"),
		                                   new TreeNode("Jamaica"),
				   new TreeNode("Colombia")};

	 // Create a list of some European countries and 
	 // store them in an array named nodEuropeans
	 TreeNode[] nodEuropeans = { new TreeNode("Italy"),
		                                    new TreeNode("Greece"),
				    new TreeNode("Spain"),
				    new TreeNode("England") };

	 // Create a list of continents, independently
	 TreeNode nodAfrica  = new TreeNode("Africa", nodAfricans);
	 TreeNode nodAmerica = new TreeNode("America", nodAmericans);
	 TreeNode nodAsica   = new TreeNode("Asia");
	 TreeNode nodEurope  = new TreeNode("Europe", nodEuropeans);

	 // Store the list of continents in an array named nodContinents
	 TreeNode[] nodContinents = { nodAfrica, nodAmerica, nodAsica, nodEurope };

	 // Create a branch named nodWorld and store the list of
	 // continents as its child
	 TreeNode nodWorld = new TreeNode("World", nodContinents);

	 // Finally, add the nodWorld branch to the tree view
	 tvwCountries.Nodes.Add(nodWorld);

	int count = tvwCountries.GetNodeCount(true);
	Text = count.ToString();
}	 

If you create a node and add it to a branch that already contains another node, the new node is referred to as a sibling to the existing child node.

 

Practical LearningPractical Learning: Creating Child Nodes

  1. To expand the list, change the Load event of the form as follows:
     
    private void Form1_Load(object sender, System.EventArgs e)
    {
    	// Create the categories of items for babies
    	TreeNode[] nodBabiesItems = { new TreeNode("Health and Care"),
    				new TreeNode("Bathing"),
    				new TreeNode("Decoration") };
    
    	// Create the types of pants for women
    	TreeNode[] nodWomenPants = { new TreeNode("Casual Pant"),
    				   new TreeNode("Professional Pant"),
    				   new TreeNode("Jean"),
    				   new TreeNode("Short") };
    
    	// Create the categories of items for women
    	TreeNode[] nodWomenItems = { new TreeNode("Dresse"),
    				   new TreeNode("Pants and Jean", nodWomenPants),
    				   new TreeNode("Shoe"),
    				   new TreeNode("Career Wear"),
    				   new TreeNode("Lingerie") };
    
    	// Create the categories of items for miscellaneous
    	TreeNode[] nodMiscItems = { new TreeNode("Cosmetic"),
    				  new TreeNode("Travel Gear"),
    				  new TreeNode("Jewelry") };
    
    	// Create a list of some of the categories of
    	// thems sold in the store
    	TreeNode nodBabies = new TreeNode("Babie", nodBabiesItems);
    	TreeNode nodTeens  = new TreeNode("Teen");
    	TreeNode nodWomen  = new TreeNode("Women", nodWomenItems);
    	TreeNode nodMen    = new TreeNode("Men");
    	TreeNode nodMisc   = new TreeNode("Miscellaneou", nodMiscItems);
    	TreeNode[] nodCategories = { nodBabies, nodTeens, nodWomen, nodMen, nodMisc };
    
    	// Create the top node of the tree
    	TreeNode nodDeptStore = new TreeNode("Store Item", nodCategories);
    	 
    	// Add the top node and its children to the tree
    	this.tvwStoreItems.Nodes.Add(nodDeptStore);
    }
  2. Execute the application to see the result
     
  3. Close the form

The Nodes of a Node

In our introduction, we saw that a node, any node, could have as many nodes as you judge necessary. To support this, the TreeNode class is equipped with a property called Nodes, which, like that of the TreeView class, is based on the TreeNodeCollection class. This allows you to refer to the list of children of the node that this Nodes property belongs to. With this information, you can further create or manipulate child nodes of any node as you wish.

Node Selection

Besides looking at a node, probably the primary action a user performs on a tree is to select an item. To select a node in the tree, the user can click it. To programmatically select a node, assign its reference to the TreeView.SelectedNode property. Here is an example:

private void btnCreate_Click(object sender, System.EventArgs e)
{
	TreeView tvwCountries = new TreeView();
	tvwCountries.Location = new Point(10, 50);
	tvwCountries.Width = 220;
	tvwCountries.Height = 260;

	Controls.Add(tvwCountries);

	TreeNode nodAfrica  = new TreeNode("Africa");
	TreeNode nodAmerica = new TreeNode("America");
	TreeNode nodEurope  = new TreeNode("Europe");
	TreeNode[] nodContinents = { nodAfrica, nodAmerica, nodEurope };
				 
	TreeNode nodWorld = new TreeNode("World", nodContinents);
	tvwCountries.Nodes.Add(nodWorld);

	tvwCountries.SelectedNode = nodAmerica;
}

After selecting a node, the tree view indicates the item selected by highlighting it. In the following picture, the Africa node is selected:

To programmatically find out what item is selected in the tree, get the value of the TreeView.SelectedNode Boolean property. If no node is selected, this property produces null. Alternatively, you can check the value of a node's TreeNode.IsSelected Boolean property to find out if it is currently selected.

Practical LearningPractical Learning: Introducing Node Selection

  1. Right-click the form and click View Code
  2. In the form's class, declare a variable of type TreeNode and named nodSelected
     
    public class Form1 : System.Windows.Forms.Form
    {
    	private System.Windows.Forms.TreeView tvwStoreItems;
    	private System.Windows.Forms.Button btnClose;
    	/// <summary>
    	/// Required designer variable.
    	/// </summary>
    	private System.ComponentModel.Container components = null;
    	TreeNode nodSelected;
    
    	public Form1()
    	{
  3. Save all

Node Edition

After locating a node, the user may want to change its text. To change the string of a node, it must be put to edit mode. To do this, you can call the TreeNode.BeginEdit() method. Its syntax is:

public void BeginEdit();

When a node is in edit mode, the caret blinks in its edit box section. The user can then type a new string or edit the existing string. After setting the (new) string, the user can press Enter or may click somewhere. At this time, you need to indicate that the user has finished this operation. To do this, you can call the TreeNode.EndEdit() method. Its syntax is:

public void EndEdit(bool cancel);

Just before this method, you can check the content of the string that was added or edited. This allows you to accept or reject the change. The argument to the EndEdit() method allows you to validate or cancel the editing action.

Node Location

As mentioned already, the nodes of a tree view are stored in a collection of type TreeNodeCollection. Every time you create a new node, it occupies a position inside the tree. Each node is represented by the Item indexed property of this collection. The first node of the tree has an index of 0.

When you call the TreeNodeCollection.Add() method to create a node, the new branch is added at the end of the list of its siblings. If you want, you can add a new child somewhere in the tree. To do this, you would call the TreeNodeCollection.Insert() method. Its syntax is:

public virtual void Insert(int index, TreeNode node);

The first argument to this method is the index that the new node will occupy when created. The second argument is a reference to the new node to be created. Here is an example of using it:

private void btnCreate_Click(object sender, System.EventArgs e)
{
	TreeView tvwCountries = new TreeView();
	tvwCountries.Location  = new Point(10, 50);
	tvwCountries.Width      = 220;
	tvwCountries.Height     = 260;

	Controls.Add(tvwCountries);

	TreeNode[] nodContinents = { new TreeNode("Africa"),
				   new TreeNode("America"),
				   new TreeNode("Asia"),
				   new TreeNode("Europe") };

	TreeNode nodWorld = new TreeNode("World", nodContinents);
	tvwCountries.Nodes.Add(nodWorld);

	tvwCountries.Nodes.Insert(1, new TreeNode("Neptune"));
}

Another technique you can use to locate a node consists of using some coordinates. To do this, you can call the TreeView.GetNodeAt() method that is overloaded with two versions whose syntaxes are:

public TreeNode GetNodeAt(Point pt);
public TreeNode GetNodeAt(int x, int y);

To use this method, you must know either the Point location or the x and y coordinates of the node. If you provide valid argumentation to this method, it returns a reference to the TreeNode located at the argument. Here is an example:

private void btnCreate_Click(object sender, System.EventArgs e)
{
	TreeView tvwCountries = new TreeView();
	tvwCountries.Location  = new Point(10, 50);
	tvwCountries.Width      = 220;
	tvwCountries.Height     = 260;
	Controls.Add(tvwCountries);

	TreeNode[] nodContinents = { new TreeNode("Africa"),
				   new TreeNode("America"),
				   new TreeNode("Asia"),
				   new TreeNode("Europe") };

	TreeNode nodWorld = new TreeNode("World", nodContinents);
	tvwCountries.Nodes.Add(nodWorld);	 

	tvwCountries.ExpandAll();

	TreeNode nodBranch = tvwCountries.GetNodeAt(22, 48);
	Text = nodBranch.Text;
}

After creating a tree, to get a reference to the first child node, you can retrieve the TreeNode.FirstNode property. You would use code as follows:

private void btnCreate_Click(object sender, System.EventArgs e)
{
	TreeView tvwCountries = new TreeView();
	tvwCountries.Location  = new Point(10, 50);
	tvwCountries.Width      = 220;
	tvwCountries.Height     = 260;

	Controls.Add(tvwCountries);

	TreeNode[] nodContinents = { new TreeNode("Africa"),
				   new TreeNode("America"),
				   new TreeNode("Asia"),
				   new TreeNode("Europe") };

	TreeNode nodWorld = new TreeNode("World", nodContinents);
	tvwCountries.Nodes.Add(nodWorld);	 

	TreeNode nodFirst = tvwCountries.Nodes[0].FirstNode;
	Text = nodFirst.Text;
}

To get a reference to the last child node, retrieve the TreeNode.LastNode property. You would use code as follows:

TreeNode nodLast = tvwCountries.Nodes[0].LastNode;
Text = nodLast.Text;

To get a reference to the sibling above a node, if any, you can retrieve its TreeNode.PrevNode property. To get a reference to the sibling below a node, if any, you can retrieve its TreeNode.NextNode property.

To find whether a tree view contains a certain node, you can call the TreeNodeCollection.Contains() method. Its syntax is:

public bool Contains(TreeNode node);

This method expects as argument a reference to the node to look for. If the tree contains that node, the method returns true. If the node is not found, this method returns false.

 

Practical LearningPractical Learning: Using the Selected Node

  1. On the form, click the tree view
  2. In the Properties window, click the Events button and double-click MouseDown
  3. Implement the MouseDown event as follows:
     
    private void tvwStoreItems_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
    {
    	this.nodSelected = this.tvwStoreItems.GetNodeAt(e.X, e.Y);
    }
  4. To add a new form, on the main menu, click Project -> Add Windows Form...
  5. In the Templates list, make sure that Windows Forms is selected and set the Name to NewCategory
  6. Click Open
  7. Design the form as follows:
     
    Department Store - New Category: Form Design
    Control Name Text Other Properties
    Label   New Category:  
    TextBox txtNewCategory   Modifiers: Public
    Button btnOK OK DialogResult: OK
    Button btnCancel Cancel DialogResult: Cancel
    Form   New Make AcceptButton: btnOK
    CancelButton: btnCancel
    FormBorderStyle: FixedDialog
    MaximizeBox: False
    MinimizeBox: False
    ShowInTaskbar: False
    StartPosition: CenterScreen
  8. Display the first form (Form1.cs [Design]). In the Windows Forms section of the Toolbox, click ContextMenu and click the form
  9. On the form, click ContextMenu and click Type Here. Create three menu items as follows:
     
    Text (Name) Shortcut
    New Category mnuNewCategory CtrlN
    Delete mnuDelCategory Del
    Remove all Items mnuDeleteAll ShiftDel
  10. On the form, click the tree view. In the Properties window, set its ContextMenu to contextMenu1
  11. Under the form, click contextMenu1. On the form, click Context Menu and double-click New Category
  12. Implement the event as follows:
     
    private void mnuNewCategory_Click(object sender, System.EventArgs e)
    {
    	if( nodSelected == null )
    		return;
    
    	this.tvwStoreItems.SelectedNode = nodSelected;
    	NewCategory dlgCategory = new NewCategory();
    
    	if( dlgCategory.ShowDialog() == DialogResult.OK )
    	{
    		if( dlgCategory.txtNewCategory.Text.Equals("") )
    			return;
    
    		this.tvwStoreItems.SelectedNode.Nodes.Add(dlgCategory.txtNewCategory.Text);
    	}
    }
  13. Execute the application
  14. Click the + button
  15. Right-click Women in the tree and click New Category
     
  16. In the New Category dialog box, type Skirts
     
  17. Press Enter
     
  18. Close the form and return to your programming environment

The Path to a Node

After a node has been added to a tree, it holds a position relative to its parent and its existence depends on that parent. To keep track of its "ancestry", each node has a path that can be used to identify its parent and its grand-parent(s), if any. To know the path of a node from itself to the root, you can access its TreeNode.FullPath property. This property produces a string made of sections separated by a specific character identified as the TreeView.PathSeparator property. By default, this character is the backslash, following the conventions of the operating system. If you want to use a different character or string, assign it to the PathSeparator property. To know what character or string a tree view is using as the separator, you can retrieve the value of its PathSeparator property.

Deleting Nodes

When a tree contains a few nodes, the user may want to delete some of them, for any reason. To delete a node, you can call the TreeNodeCollection.Remove() method. Its syntax is:

public void Remove(TreeNode node);

This method expects a reference to the node you want to delete. Another solution you can use would consist of locating the node by its index. To do this, you would call the TreeNodeCollection.RemoveAt() method. Its syntax is:

public virtual void RemoveAt(int index);

When calling this method, pass the index of the node to be deleted. If you are already at that node and you want to remove it, you can call the TreeNode.Remove() method. Its syntax is:

public void Remove();

One of the characteristics of a tree in the real world is that, if you cut a branch, the branches attached to it and their leaves are cut too. In the same way, if you call any of these Remove() or RemoveAt() methods to delete a node, its children, if any, would be deleted too.

To remove all nodes of a tree view, you can call the TreeNodeCollection.Clear() method. Its syntax is:

public virtual void Clear();

This method is used to get rid of all nodes of a tree.

Practical LearningPractical Learning: Deleting a Node

  1. Display the first form. Under the form, click contextMenu1, then click Context Menu on the form and double-click Delete
  2. Implement the event as follows:
     
    private void mnuDelCategory_Click(object sender, System.EventArgs e)
    {
    	// Make sure a node is selected
    	if( nodSelected != null )
    		this.nodSelected.Remove();
    }
  3. Return to the form. Click Context Menu on the form and double-click Remove all Items
  4. Implement the event as follows:
     
    private void mnuDeleteAll_Click(object sender, System.EventArgs e)
    {
    	this.tvwStoreItems.Nodes.Clear();
    }
  5. Execute the application and try deleting an item

Visual Feedback of Nodes

 

Hot Tracking

In order to select an item, the user must click it or navigate to it using the keyboard. Alternative, if you want the items to be underlined when the mouse passes over them, set to true the TreeView.HotTracking Boolean property. Its default value is false. Here is an example:

private void btnCreate_Click(object sender, System.EventArgs e)
{
	TreeView tvwCountries = new TreeView();
	tvwCountries.Location  = new Point(10, 50);
	tvwCountries.Width      = 220;
	tvwCountries.HotTracking = true;

	Controls.Add(tvwCountries);

	TreeNode[] nodContinents = { new TreeNode("Africa"),
				   new TreeNode("America"),
				   new TreeNode("Asia"),
				   new TreeNode("Europe") };

	TreeNode nodWorld = new TreeNode("World", nodContinents);
	tvwCountries.Nodes.Add(nodWorld);
}

The Intermediary Lines of Related Nodes

As mentioned already, a tree view appears as a list of items arranged like a tree. This implies a relationship of parent-child among the items in the control. To indicate this relationship between two nodes, a line is drawn from one to another. Based on this, a line from a node on top to another node under it indicates that the one on top is the parent to the one under it.

The presence or absence of the lines among related nodes is controlled by the TreeView.ShowLines Boolean property. By default, this property is set to true. If this property is set to false, the lines between the nodes would not display. Here is an example:

private void btnCreate_Click(object sender, System.EventArgs e)
{
	TreeView tvwCountries = new TreeView();
	tvwCountries.Location  = new Point(10, 50);
	tvwCountries.Width      = 220;
	tvwCountries.HotTracking = true;
	 tvwCountries.ShowLines = false;

	Controls.Add(tvwCountries);

	TreeNode[] nodContinents = { new TreeNode("Africa"),
				   new TreeNode("America"),
				   new TreeNode("Asia"),
				   new TreeNode("Europe") };

	TreeNode nodWorld = new TreeNode("World", nodContinents);
	tvwCountries.Nodes.Add(nodWorld);	 
}

The Root Lines

If you create a tree that has more than one root, a line is drawn among those root nodes. Here is an example:

The presence or absence of this type of line is controlled by the TreeView.ShowRootLines Boolean property.

Node Indentation

Indentation is the ability for a child node to be aligned to the right with regards to its parent. The general distance from the left border of the parent to the left border of the child is partially controlled by the TreeView.Indent property which is an integer. If the default distance doesn't suit you, you can change it by assigning a positive number to the control's Indent property.

Full Row Selection

When the user clicks an item, that node becomes highlighted for the length of its string. If you want, you can show the highlighting on the selected node but from the left to the right borders of the tree view. To do this, you can set the TreeView.FullRowSelect Boolean property to true. Its default value is false. For the TreeView.FullRowSelect property to work, the ShowLines property must be set to false. Here is an example:

private void btnCreate_Click(object sender, System.EventArgs e)
{
	TreeView tvwCountries = new TreeView();
	tvwCountries.Location  = new Point(10, 50);
	tvwCountries.Width      = 220;
	tvwCountries.HotTracking = true;
	 tvwCountries.ShowLines = false;
	 tvwCountries.FullRowSelect = true;

	Controls.Add(tvwCountries);

	TreeNode[] nodContinents = { new TreeNode("Africa"),
				   new TreeNode("America"),
				   new TreeNode("Asia"),
				   new TreeNode("Europe") };

	TreeNode nodWorld = new TreeNode("World", nodContinents);
	tvwCountries.Nodes.Add(nodWorld);
}

Hiding Selection After Losing Focus

We saw that, to select an item, the user can click it. If the user clicks another control, the node that was selected in the tree view loses its highlighting because the control has lost focus. When the focus moves to another control, if you want the selected node of the tree view to preserve its highlighting, set to false the TreeView.HideSelection Boolean property. Its default value is true.

The + and - Buttons

At this time, we have seen that some nodes have children and some don't. When a node has at least one child, the node indicates this by displaying a + button. If the user clicks the + button, the node expands, displays a list of its children, and the button becomes -. The presence or absence of the + and - buttons is controlled by the TreeView.ShowPlusMinus Boolean property. By default, this property is set to true. If you don't want the parent nodes to display the + or - button, set this property to false.

Expanding and Collapsing Tree Nodes

When a node displays a + button and the user clicks that button, the node displays its child(ren). This action is referred to as expanding the node. To programmatically expand a node, call its TreeNode.Expand() method. Its syntax is:

public void Expand();

This method only expands the node that calls it but if its children have their own children, they are not expanded.  To expand a node and its children that have nodes, you can call its TreeNode.ExpandAll() method. Its syntax is:

public void ExpandAll();

To find out if a node is expanded, check the value of its TreeNode.IsExpanded property.

To expand other nodes of the tree view, the user can continue clicking each node that has a + button as necessary. To programmatically expand all nodes of a tree view, call its TreeView.ExpandAll() method. Its syntax is:

public void ExpandAll();

If a node is displaying a - button, it indicates that it is showing the list of its children. To hide the list, the user can click the - button. This action is referred to as collapsing the node. To programmatically collapse a node, call its TreeNode.Collapse() method whose syntax is:

public void Collapse();

The user can do this for each node that is expanded. To programmatically collapse all nodes of a tree view, call its TreeView.CollapseAll() method. Its syntax is:

public void CollapseAll();

Tree Nodes and Check Boxes

Besides the strings (and some small pictures as we will see later), the nodes of a tree view can display a check box on their left side. The presence or absence of the check box is controlled by the CheckBoxes Boolean property whose default value is false. If you want to display the check boxes, set this property to true. Here is an example:

private void btnCreate_Click(object sender, System.EventArgs e)
{
	TreeView tvwCountries = new TreeView();
	tvwCountries.Location  = new Point(10, 50);
	tvwCountries.Width      = 220;
	tvwCountries.CheckBoxes = true;
	Controls.Add(tvwCountries);

	TreeNode[] nodContinents = { new TreeNode("Africa"),
				   new TreeNode("America"),
				   new TreeNode("Asia"),
				   new TreeNode("Europe") };

	TreeNode nodWorld = new TreeNode("World", nodContinents);
	tvwCountries.Nodes.Add(nodWorld);
}

If you equip the nodes with check boxes, the user can click an item to select it independently of the check box. The user can also click the check box, which would place a check mark in the box. To programmatically check the box, you can assign a true value to the node's Checked property.

When a check mark has been placed in a node's check box, the tree view fires an AfterCheck event, which is handled by the TreeViewEventHandler delegate. The AfterCheck event is carried by the TreeViewEventArgs class. One of properties of this class is called Action, which specifies why or how the event occurred. The Action property is in fact a value based on the TreeViewAction enumerator. Its members are:

ByKeyboard: This indicates that the event was fired by pressing a key

ByMouse: This indicates that the event was fired based on an action on the mouse

Collapse: This indicates that event was fired when the tree collapsed

Expand: This indicates that the event was fired when the tree expanded

Unknown: None of the above reasons caused the event, but the event was fired

The other property of the TreeViewEventArgs class is called Node. This member is of type TreeNode. It carries a reference to the node that fired the event, whether it was clicked, checked, expanded, or collapsed.

To programmatically find out if a node is checked, check the value of its Checked property.

 

Tree Nodes and Icons

Each of the nodes we have used so far displayed a simple piece of text. To enhance the appearance of a node, besides its text, you can display a small icon to the left of its string. To do this, you must first create an ImageList control and assign it to the TreeView.ImageList property.

When creating a node, if you plan to display an icon next to it, you can use the following constructor of the TreeNode class:

public TreeNode(String text, int imageIndex, int selectedImageIndex);

This constructor allows you to specify the text that the node will display, the index of the picture it will use in the ImageList property, and the picture it will display when it is selected.

If you are creating a node with its children and you want to specify its pictures, use the following constructor of the TreeNode class:

public TreeNode(String text,
                            int imageIndex,
                            int selectedImageIndex,
                            TreeNode children[]);

Just as done previously, after defining the TreeNode object, you can add it to the tree by passing it to the TreeNodeCollection.Add() method. In the same way, you can create an array of TreeNode objects and pass it to the TreeNodeCollection.AddRange() method.

 

Practical LearningPractical Learning: Associating Icons With Nodes

  1. To create an icon, on the main menu, click File -> New -> File...
  2. In the New File dialog box, click Icon File and click Open
  3. Right-click the white area and click Delete Image Type
  4. Design the 16x16, 16 colors version of the icon as follows:
     
  5. To save the new icon, on the main menu, click File -> Save Icon1 As...
  6. Locate the folder that contains the current project and display it in the Save In combo box
  7. Double-click its bin followed by its debug folder to display it in the Save In combo box
  8. Change the name of the file to StoreDef.ico and click Save
  9. Follow the same steps to create a new Icon File. Delete its 32x32 pixels version and design its 16x16 version as follows:
     
  10. Save it as StoreSel.ico
  11. Follow the same steps to create a new Icon File. Delete its 32x32 pixels version and design its 16x16 version as follows:
     
  12. Save it as CatDef.ico
  13. Follow the same steps to create a new Icon File. Delete its 32x32 pixels version and design its 16x16 version as follows:
     
  14. Save it as CatSel.ico
  15. Follow the same steps to create a new Icon File. Delete its 32x32 pixels version and design its 16x16 version as follows:
     
  16. Save it as GroupDef.ico
  17. Follow the same steps to create a new Icon File. Delete its 32x32 pixels version and design its 16x16 version as follows:
     
  18. Save it as GroupSel.ico 
  19. Follow the same steps to create a new Icon File. Delete its 32x32 pixels version and design its 16x16 version as follows:
     
  20. Save it as LevelDef.ico
  21. Follow the same steps to create a new Icon File. Delete its 32x32 pixels version and design its 16x16 version as follows:
     
  22. Save it as LevelSel.ico
  23. Display the first form.
    In the Toolbox, click ImageList and click the form
  24. In the Properties window, click the ellipsis button of the Images field
  25. In Image Collection Editor, click Add
  26. Locate the folder that contains the icons you created and display it in the Look In combo box
  27. Select StoreDef.ico and click Open
  28. In the same way, add the other pictures in the following order: StoreSel.ico, StoreSel.ico, CatDef.ico, CatSel.ico, GroupDef.ico, GroupSel.ico, LevelDef.ico, LevelSel.ico
     
    Image Collection Editor
  29. Click OK
  30. In the form, click the tree view and, in the Properties window, set its ImageList to imageList1
  31. Double-click an unoccupied area of the form and change its Load event as follows:
     
    private void Form1_Load(object sender, System.EventArgs e)
    {
    	// Create the categories of items for babies
    	TreeNode[] nodBabiesItems = { new TreeNode("Health and Care", 4, 5),
    				new TreeNode("Bathing", 4, 5),
    				new TreeNode("Decoration", 4, 5) };
    
    	// Create the types of pants for women
    	TreeNode[] nodWomenPants = { new TreeNode("Casual Pant", 6, 7),
    				   new TreeNode("Professional Pant", 6, 7),
    				   new TreeNode("Jean", 6, 7),
    				   new TreeNode("Short", 6, 7) };
    
    	// Create the categories of items for women
    	TreeNode[] nodWomenItems = { new TreeNode("Dresse", 4, 5),
    				   new TreeNode("Pants and Jean", 4, 5, nodWomenPants),
    				   new TreeNode("Shoe", 4, 5),
    				   new TreeNode("Career Wear", 4, 5),
    				   new TreeNode("Lingerie", 4, 5) };
    
    	// Create the categories of items for miscellaneous
    	TreeNode[] nodMiscItems = { new TreeNode("Cosmetic", 4, 5),
    				  new TreeNode("Travel Gear", 4, 5),
    				  new TreeNode("Jewelry", 4, 5) };
    
    	// Create a list of some of the categories of
    	// thems sold in the store
    	TreeNode nodBabies = new TreeNode("Babie", 2, 3, nodBabiesItems);
    	TreeNode nodTeens  = new TreeNode("Teen", 2, 3);
    	TreeNode nodWomen  = new TreeNode("Women", 2, 3, nodWomenItems);
    	TreeNode nodMen    = new TreeNode("Men", 2, 3);
    	TreeNode nodMisc   = new TreeNode("Miscellaneou", 2, 3, nodMiscItems);
    	TreeNode[] nodCategories = { nodBabies, nodTeens, nodWomen, nodMen, nodMisc };
    
    	// Create the top node of the tree
    	TreeNode nodDeptStore = new TreeNode("Store Item", 0, 1, nodCategories);
    	 
    	// Add the top node and its children to the tree
    	this.tvwStoreItems.Nodes.Add(nodDeptStore);
    }
  32. Execute the application to test it
     
  33. Close the form and return to your programming environment
 

Home Copyright © 2004-2010 FunctionX, Inc.