Home

.NET 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: System::Void btnCreate_Click(System::Object *  sender, System::EventArgs *  e)
{
	 TreeView *tvwCountries = new TreeView();
	 tvwCountries->Location  = 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: System::Void btnClose_Click(System::Object *  sender, System::EventArgs *  e)
    {
    	 Close();
    }
  7. Save all
 

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:

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 the root node. Here is an example of calling it:
private: System::Void btnCreate_Click(System::Object *  sender, System::EventArgs *  e)
{
	 TreeView *tvwCountries = new TreeView();
	 tvwCountries->Location = Point(10, 50);
	 tvwCountries->Width = 220;
	 tvwCountries->Height = 260;

	 Controls->Add(tvwCountries);

	 tvwCountries->Nodes->Add(S"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: System::Void btnCreate_Click(System::Object *  sender, System::EventArgs *  e)
{
	 TreeView *tvwCountries = new TreeView();
	 tvwCountries->Location = Point(10, 50);
	 tvwCountries->Width = 220;
	 tvwCountries->Height = 260;

	 Controls->Add(tvwCountries);

	 TreeNode *nodElement = new TreeNode(S"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:

System::Void btnCreate_Click(System::Object *  sender, System::EventArgs *  e)
{
	 TreeView *tvwCountries = new TreeView();
	 tvwCountries->Location = Point(10, 50);
	 tvwCountries->Width = 220;
	 tvwCountries->Height = 260;

	 Controls->Add(tvwCountries);

	 TreeNode *nodElement = new TreeNode();
	 nodElement->Text = S"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: System::Void btnCreate_Click(System::Object *  sender, System::EventArgs *  e)
{
	 TreeView *tvwCountries = new TreeView();
	 tvwCountries->Location = Point(10, 50);
	 tvwCountries->Width = 220;

	 Controls->Add(tvwCountries);

	 tvwCountries->Nodes->Add(S"World");
	 tvwCountries->Nodes->Add(S"Jupiter");
	 tvwCountries->Nodes->Add(S"Neptune");
	 tvwCountries->Nodes->Add(S"Uranus");
}

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: System::Void btnCreate_Click(System::Object *  sender, System::EventArgs *  e)
{
	 TreeView *tvwCountries = new TreeView();
	 tvwCountries->Location = Point(10, 50);
	 tvwCountries->Width = 220;
	 tvwCountries->Height = 260;

	 Controls->Add(tvwCountries);

	 TreeNode* nodPlanets[] = { new TreeNode(S"World"), new TreeNode(S"Jupiter"),
				 new TreeNode(S"Neptune"), new TreeNode(S"Uranus") };
	 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: System::Void Form1_Load(System::Object *  sender, System::EventArgs *  e)
    {
    	 TreeNode *nodDeptStore = new TreeNode(S"Store Items");
    
    	 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: System::Void btnCreate_Click(System::Object *  sender, System::EventArgs *  e)
{
	 TreeView *tvwCountries = new TreeView();
	 tvwCountries->Location = Point(10, 50);
	 tvwCountries->Width = 220;

	 Controls->Add(tvwCountries);

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

	 TreeNode *nodWorld = new TreeNode(S"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: System::Void btnCreate_Click(System::Object *  sender, System::EventArgs *  e)
{
	 TreeView *tvwCountries = new TreeView();
	 tvwCountries->Location = 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(S"Senegal"),
		                               new TreeNode(S"Botswana"),
			               new TreeNode(S"Ghana"),
			               new TreeNode(S"Morocco") };

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

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

	 // Create a list of continents, independently
	 TreeNode *nodAfrica  = new TreeNode(S"Africa", nodAfricans);
	 TreeNode *nodAmerica = new TreeNode(S"America", nodAmericans);
	 TreeNode *nodAsica   = new TreeNode(S"Asia");
	 TreeNode *nodEurope  = new TreeNode(S"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(S"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: System::Void btnCreate_Click(System::Object *  sender, System::EventArgs *  e)
{
	 TreeView *tvwCountries = new TreeView();
	 tvwCountries->Location = 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(S"Senegal"),
		                               new TreeNode(S"Botswana"),
			               new TreeNode(S"Ghana"),
			               new TreeNode(S"Morocco") };

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

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

	 // Create a list of continents, independently
	 TreeNode *nodAfrica  = new TreeNode(S"Africa", nodAfricans);
	 TreeNode *nodAmerica = new TreeNode(S"America", nodAmericans);
	 TreeNode *nodAsica   = new TreeNode(S"Asia");
	 TreeNode *nodEurope  = new TreeNode(S"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(S"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: System::Void Form1_Load(System::Object *  sender, System::EventArgs *  e)
    {
    	 // Create the categories of items for babies
    	 TreeNode *nodBabiesItems[] = { new TreeNode(S"Health and Care"),
    				  new TreeNode(S"Bathing"),
    			                      new TreeNode(S"Decorations") };
    
    	 // Create the types of pants for women
    	 TreeNode *nodWomenPants[] = { new TreeNode(S"Casual Pants"),
    				  new TreeNode(S"Professional Pants"),
    			                      new TreeNode(S"Jeans"),
    			                      new TreeNode(S"Shorts") };
    
    	 // Create the categories of items for women
    	 TreeNode *nodWomenItems[] = { new TreeNode(S"Dresses"),
    	                      new TreeNode(S"Pants and Jeans", nodWomenPants),
    				  new TreeNode(S"Shoes"),
    				  new TreeNode(S"Career Wear"),
    				  new TreeNode(S"Lingerie") };
    
    	 // Create the categories of items for miscellaneous
    	 TreeNode *nodMiscItems[] = { new TreeNode(S"Cosmetics"),
    				  new TreeNode(S"Travel Gear"),
    			                      new TreeNode(S"Jewelry") };
    
    	 // Create a list of some of the categories of
    	 // thems sold in the store
    	 TreeNode *nodBabies = new TreeNode(S"Babies", nodBabiesItems);
    	 TreeNode *nodTeens  = new TreeNode(S"Teens");
    	 TreeNode *nodWomen  = new TreeNode(S"Women", nodWomenItems);
    	 TreeNode *nodMen    = new TreeNode(S"Men");
    	 TreeNode *nodMisc   = new TreeNode(S"Miscellaneous", nodMiscItems);
     TreeNode *nodCategories[] = { nodBabies, nodTeens, nodWomen, nodMen, nodMisc };
    
    	 // Create the top node of the tree
    	 TreeNode *nodDeptStore = new TreeNode(S"Store Items", 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: System::Void btnCreate_Click(System::Object *  sender, System::EventArgs *  e)
{
	 TreeView *tvwCountries = new TreeView();
	 tvwCountries->Location = Point(10, 50);
	 tvwCountries->Width = 220;
	 tvwCountries->Height = 260;

	 Controls->Add(tvwCountries);

	 TreeNode *nodAfrica  = new TreeNode(S"Africa");
	 TreeNode *nodAmerica = new TreeNode(S"America");
	 TreeNode *nodEurope  = new TreeNode(S"Europe");
	 TreeNode *nodContinents[] = { nodAfrica, nodAmerica, nodEurope };
				 
	 TreeNode *nodWorld = new TreeNode(S"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 pointer to TreeNode named nodSelected
     
    private:
    		/// <summary>
    		/// Required designer variable.
    		/// </summary>
    		System::ComponentModel::Container * components;
    		TreeNode* nodSelected;
  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: System::Void btnCreate_Click(System::Object *  sender, System::EventArgs *  e)
{
	 TreeView *tvwCountries = new TreeView();
	 tvwCountries->Location  = Point(10, 50);
	 tvwCountries->Width      = 220;
	 tvwCountries->Height     = 260;

	 Controls->Add(tvwCountries);

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

	 TreeNode *nodWorld = new TreeNode(S"World", nodContinents);
	 tvwCountries->Nodes->Add(nodWorld);

	 tvwCountries->Nodes->Insert(1, new TreeNode(S"Neptune"));
}

Another technique you can use to locate a node consists of using some coordinates. To to 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: System::Void btnCreate_Click(System::Object *  sender, System::EventArgs *  e)
{
	 TreeView *tvwCountries = new TreeView();
	 tvwCountries->Location  = Point(10, 50);
	 tvwCountries->Width      = 220;
	 tvwCountries->Height     = 260;

	 Controls->Add(tvwCountries);

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

	 TreeNode *nodWorld = new TreeNode(S"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:

TreeNode *nodFirst = tvwCountries->Nodes->Item[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->Item[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: System::Void tvwStoreItems_MouseDown(System::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 New Item...
  5. In the Templates list, click Windows Forms (.NET) 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.h [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. In the top section of the file, type #include "NewCategory.h"
  13. Implement the event as follows:
     
    private: System::Void mnuNewCategory_Click(System::Object *  sender, System::EventArgs *  e)
    {
    	 if( nodSelected == 0 )
    		 return;
    
    	 this->tvwStoreItems->SelectedNode = nodSelected;
    	 NewCategory *dlgCategory = new NewCategory();
    
    	 if( dlgCategory->ShowDialog() == DialogResult::OK )
    	 {
    		 if( dlgCategory->txtNewCategory->Text->Equals(S"") )
    			 return;
    
               this->tvwStoreItems->SelectedNode->Nodes->Add(dlgCategory->txtNewCategory->Text);
    	 }
    }
  14. Execute the application
  15. Click the + button
  16. Right-click Women in the tree and click New Category
     
  17. In the New Category dialog box, type Skirts
     
  18. Press Enter
     
  19. 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 index of the node and using it. 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 other 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 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 ContextMenu on the form and double-click Delete
  2. Implement the event as follows:
     
    private: System::Void mnuDelCategory_Click(System::Object *  sender, System::EventArgs *  e)
    {
    	// Make sure a node is selected
    	if( nodSelected )
    	 	this->nodSelected->Remove();
    }
  3. Return to the form. Click ContextMenu on the form and double-click Remove all Items
  4. Implement the event as follows:
     
    private: System::Void mnuDeleteAll_Click(System::Object *  sender, System::EventArgs *  e)
    {
    	 this->tvwStoreItems->Nodes->Clear();
    }
  5. Execute the application and try deleting an item

Visual Feedback of Nodes

In order to select an item, the user must click it or navigate to it using the keyboard. Alternative, if you want, you can cause the items to be underlined when the mouse passes over them:

To produce this effect, you can set to true the TreeView::HotTracking Boolean property. Its default value is false.

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 among the nodes would not display. Here is an example:

private: System::Void btnCreate_Click(System::Object *  sender, System::EventArgs *  e)
{
	 TreeView *tvwCountries = new TreeView();
	 tvwCountries->Location = Point(10, 50);
	 tvwCountries->Width = 220;
	 tvwCountries->Height = 260;
	 tvwCountries->ShowLines = false;

	 Controls->Add(tvwCountries);

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

	 tvwCountries->SelectedNode = nodAmerica;
}

In the same way, 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.

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.

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: System::Void btnCreate_Click(System::Object *  sender, System::EventArgs *  e)
{
	 TreeView *tvwCountries = new TreeView();
	 tvwCountries->Location = Point(10, 50);
	 tvwCountries->Width = 220;
	 tvwCountries->Height = 260;
	 tvwCountries->ShowLines = false;
	 tvwCountries->FullRowSelect = true;

	 Controls->Add(tvwCountries);

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

	 tvwCountries->SelectedNode = nodAmerica;
}

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.

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: System::Void btnCreate_Click(System::Object *  sender, System::EventArgs *  e)
{
	 TreeView *tvwCountries = new TreeView();
	 tvwCountries->Location = Point(10, 50);
	 tvwCountries->Width = 220;
	 tvwCountries->Height = 260;
	 tvwCountries->CheckBoxes = true;

	 Controls->Add(tvwCountries);

	 TreeNode *nodAfrica  = new TreeNode(S"Africa");
	 TreeNode *nodAmerica = new TreeNode(S"America");
	 TreeNode *nodEurope  = new TreeNode(S"Europe");
	 TreeNode *nodContinents[] = { nodAfrica, nodAmerica, nodEurope };
				 
	 TreeNode *nodWorld = new TreeNode(S"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 a mouse movement

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

Expand: This indicates that 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 Project -> Add Resource... In the Add Resource dialog box, click Icon and click New
  2. Right-click a white area in the main window and click New Item Type... In the New Icon Image Type dialog box, make sure 16x16, 16 colors is selected and click OK
  3. In the Properties window, change the Filename to StoreDef.ico and design the icon as follows:
     
  4. Right-click the white area -> Current Icon Image Types -> 32x32, 16 Colors
  5. Right-click the white area and click Delete Image Type
  6. To create another icon, on the main menu, click Project -> Add Resource...In the Add Resource dialog box, click Icon and click New
  7. As done above, display the New Icon Image dialog box and select 16x16, 16 colors
  8. In the Properties window, change the Filename to StoreSel.ico and design it as follows:
     
  9. Right-click the white area -> Current Icon Image Types -> 32x32, 16 Colors
  10. Right-click the white area and click Delete Image Type
  11. To create another icon, on the main menu, click Project -> Add Resource...In the Add Resource dialog box, click Icon and click New
  12. As done above, display the New Icon Image dialog box and select 16x16, 16 colors
  13. In the Properties window, change the Filename to CatDef.ico and design it as follows:
     
  14. Right-click the white area -> Current Icon Image Types -> 32x32, 16 Colors
  15. Right-click the white area and click Delete Image Type
  16. To create another icon, on the main menu, click Project -> Add Resource...In the Add Resource dialog box, click Icon and click New
  17. As done above, display the New Icon Image dialog box and select 16x16, 16 colors
  18. In the Properties window, change the Filename to CatSel.ico and design it as follows:
     
  19. Right-click the white area -> Current Icon Image Types -> 32x32, 16 Colors
  20. Right-click the white area and click Delete Image Type
  21. To create another icon, on the main menu, click Project -> Add Resource...In the Add Resource dialog box, click Icon and click New
  22. As done above, display the New Icon Image dialog box and select 16x16, 16 colors
  23. In the Properties window, change the Filename to GroupDef.ico and design it as follows:
     
  24. Right-click the white area -> Current Icon Image Types -> 32x32, 16 Colors
  25. Right-click the white area and click Delete Image Type
  26. To create another icon, on the main menu, click Project -> Add Resource...In the Add Resource dialog box, click Icon and click New
  27. As done above, display the New Icon Image dialog box and select 16x16, 16 colors
  28. In the Properties window, change the Filename to GroupSel.ico 
  29.  and design it as follows:
     
  30. Right-click the white area -> Current Icon Image Types -> 32x32, 16 Colors
  31. Right-click the white area and click Delete Image Type
  32. To create another icon, on the main menu, click Project -> Add Resource...In the Add Resource dialog box, click Icon and click New
  33. As done above, display the New Icon Image dialog box and select 16x16, 16 colors
  34. In the Properties window, change the Filename to LevelDef.ico and design it as follows:
     
  35. Right-click the white area -> Current Icon Image Types -> 32x32, 16 Colors
  36. Right-click the white area and click Delete Image Type
  37. To create another icon, on the main menu, click Project -> Add Resource...In the Add Resource dialog box, click Icon and click New
  38. As done above, display the New Icon Image dialog box and select 16x16, 16 colors
  39. In the Properties window, change the Filename to LevelSel.ico and design it as follows:
     
  40. Right-click the white area -> Current Icon Image Types -> 32x32, 16 Colors
  41. Right-click the white area and click Delete Image Type
  42. Save all
  43. Display the first form.
    In the Toolbox, click ImageList and click the form
  44. In the Properties window, click the ellipsis button of the Images field
  45. In Image Collection Editor, click Add
  46. Locate the folder that contains the current project and display it in the Look In combo box
  47. Select StoreDef.ico and click Open
  48. 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
     
  49. Click OK
  50. In the form, click the tree view and, in the Properties window, set its ImageList to imageList1
  51. Double-click an unoccupied area of the form and change its Load event as follows:
     
    private: System::Void Form1_Load(System::Object *  sender, System::EventArgs *  e)
    {
    	 // Create the categories of items for babies
    	 TreeNode *nodBabiesItems[] = { new TreeNode(S"Health and Care", 4, 5),
    				  new TreeNode(S"Bathing", 4, 5),
    			                      new TreeNode(S"Decorations", 4, 5) };
    
    	 // Create the types of pants for women
    	 TreeNode *nodWomenPants[] = { new TreeNode(S"Casual Pants", 6, 7),
    				  new TreeNode(S"Professional Pants", 6, 7),
    			                      new TreeNode(S"Jeans", 6, 7),
    			                      new TreeNode(S"Shorts", 6, 7) };
    
    	 // Create the categories of items for women
    	 TreeNode *nodWomenItems[] = { new TreeNode(S"Dresses", 4, 5),
    			                      new TreeNode(S"Pants and Jeans", 4, 5, nodWomenPants),
    				  new TreeNode(S"Shoes", 4, 5),
    				  new TreeNode(S"Career Wear", 4, 5),
    				  new TreeNode(S"Lingerie", 4, 5) };
    
    	 // Create the categories of items for miscellaneous
    	 TreeNode *nodMiscItems[] = { new TreeNode(S"Cosmetics", 4, 5),
    				  new TreeNode(S"Travel Gear", 4, 5),
    			                      new TreeNode(S"Jewelry", 4, 5) };
    
    	 // Create a list of some of the categories of
    	 // items sold in the store
    	 TreeNode *nodBabies = new TreeNode(S"Babies", 2, 3, nodBabiesItems);
    	 TreeNode *nodTeens  = new TreeNode(S"Teens", 2, 3);
    	 TreeNode *nodWomen  = new TreeNode(S"Women", 2, 3, nodWomenItems);
    	 TreeNode *nodMen    = new TreeNode(S"Men", 2, 3);
    	 TreeNode *nodMisc   = new TreeNode(S"Miscellaneous", 2, 3, nodMiscItems);
    	 TreeNode *nodCategories[] = { nodBabies, nodTeens, nodWomen, nodMen, nodMisc };
    
    	 // Create the top node of the tree
    	TreeNode *nodDeptStore = new TreeNode(S"Store Items", 0, 1, nodCategories);
    	 
    	 // Add the top node and its children to the tree
    	 this->tvwStoreItems->Nodes->Add(nodDeptStore);
    }
  52. Execute the application to test it
     
  53. Close the form and return to your programming environment
 

Home Copyright © 2004-2010 FunctionX, Inc.