Home

Windows Controls: The Tree View

 

Tree View Fundamentals

 

Description

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 equivalent to programmatically declaring a variable of type 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() member function. Here is an example:

#include <windows.h>

#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;

public ref class CExercise : public Form
{
private:
    TreeView ^ tvwCountries;

public:
    CExercise()
    {
	InitializeComponent();
    }

private:
    void InitializeComponent()
    {
        tvwCountries = gcnew TreeView;

        tvwCountries->Location = Point(12, 12);
        tvwCountries->Width = 210;
        tvwCountries->Height = 230;

        Controls->Add(tvwCountries);
        
        Text = "Countries Statistics";
        Size = System::Drawing::Size(242, 280);

    }
};

[STAThread]
int APIENTRY WinMain(HINSTANCE hInstance,
		     HINSTANCE hPrevInstance,
		     LPSTR lpCmdLine,
		     int nCmdShow)
{
    Application::Run(gcnew CExercise);

    return 0;
}

This would produce:

Countries Statistics

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.

Introduction to Creating Tree View Nodes

 

Visually Creating Nodes

To create the nodes of a tree view, Microsoft Visual Studio provides a convenient dialog box you can use at design time. To display it, after adding a tree view control to a form:

  • On the form, right-click the tree view and click Edit Nodes...
  • On the form, click the tree view to select it:
    • In the Properties window, click the ellipsis button of the Nodes field
    • Under the Properties window, click Edit Nodes...

This would open the TreeNode Editor:

Tree Node Editor

The primary characteristic of a node is the text it displays. At design time and in the TreeNode Editor, to create a node, 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, on the right side, click Name and enter the string you wish.

Programmatically Creating Nodes

The branches of a tree view are stored in a property called Nodes. The Nodes property is an object based on the TreeNodeCollection class. The TreeNodeCollection class implements the IList, the ICollection, and the IEnumerable interfaces.

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() member function which is overloaded with two versions. One of the versions of this member function uses the following syntax:

public:
    virtual TreeNode^ Add(String^ text);

This member function takes as argument the string that the branch will display. This member function is also the prime candidate to create a root node. Here is an example of calling it:

void InitializeComponent()
{
        Text = "Countries Statistics";
        Size = System::Drawing::Size(242, 280);

        tvwCountries = gcnew TreeView;
        tvwCountries->Location = Point(12, 12);
        tvwCountries->Width = 210;
        tvwCountries->Height = 230;

        tvwCountries->Nodes->Add("World");

        Controls->Add(tvwCountries);
}

This would produce:

Countries Statistics

A Node and its Children

 

Introduction

The other version of the TreeNodeCollection::Add() member function uses the following syntax:

public:
    virtual int Add(TreeNode^ node);

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

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:

void InitializeComponent()
{
        Text = "Countries Statistics";
        Size = System::Drawing::Size(242, 280);

        tvwCountries = gcnew TreeView;
        tvwCountries->Location = Point(12, 12);
        tvwCountries->Width = 210;
        tvwCountries->Height = 230;

        TreeNode ^ nodElement = gcnew TreeNode("World");
        tvwCountries->Nodes->Add(nodElement);

        Controls->Add(tvwCountries);
}

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:

void InitializeComponent()
{
        Text = "Countries Statistics";
        Size = System::Drawing::Size(242, 280);

        tvwCountries = gcnew TreeView;
        tvwCountries->Location = Point(12, 12);
        tvwCountries->Width = 210;
        tvwCountries->Height = 230;

        TreeNode ^ nodElement = gcnew TreeNode;
        nodElement->Text = "World";
        tvwCountries->Nodes->Add(nodElement);

        Controls->Add(tvwCountries);
}

Just as we called the TreeNodeCollection::Add() member function to create a branch, you can call it as many times as necessary to create additional branches. Here is an example:

void InitializeComponent()
{
        Text = "Countries Statistics";
        Size = System::Drawing::Size(242, 280);

        tvwCountries = gcnew TreeView;
        tvwCountries->Location = Point(12, 12);
        tvwCountries->Width = 210;
        tvwCountries->Height = 230;

        tvwCountries->Nodes->Add("World");
        tvwCountries->Nodes->Add("Jupiter");
        tvwCountries->Nodes->Add("Neptune");
        tvwCountries->Nodes->Add("Uranu");

        Controls->Add(tvwCountries);
}

This would produce:

Countries Statistics

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() member function. The syntax of this member function is:

public:
    virtual void AddRange(array>TreeNode^<^ nodes);

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

void InitializeComponent()
{
        Text = "Countries Statistics";
        Size = System::Drawing::Size(242, 280);

        tvwCountries = gcnew TreeView;
        tvwCountries->Location = Point(12, 12);
        tvwCountries->Width = 210;
        tvwCountries->Height = 230;

        array<TreeNode ^> ^ nodPlanets =
        {
            gcnew TreeNode("World"),
	    gcnew TreeNode("Jupiter"),
            gcnew TreeNode("Neptune"),
	    gcnew TreeNode("Uranu")
        };
        tvwCountries->Nodes->AddRange(nodPlanets);

        Controls->Add(tvwCountries);
}

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() member function. As its syntax indicates, this member function 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, array<TreeNode^>^ children);

The first argument of this member function 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() member function as we did earlier. Here is an example:

void InitializeComponent()
{
        Text = "Countries Statistics";
        Size = System::Drawing::Size(242, 280);

        tvwCountries = gcnew TreeView;
        tvwCountries->Location = Point(12, 12);
        tvwCountries->Width = 210;
        tvwCountries->Height = 100;

        array<TreeNode ^> ^ nodContinents =
        {
            gcnew TreeNode("Africa"),
            gcnew TreeNode("America"),
            gcnew TreeNode("Asia"),
            gcnew TreeNode("Europe")
        };

        TreeNode ^ nodWorld = gcnew TreeNode("World", nodContinents);
        tvwCountries->Nodes->Add(nodWorld);

        Controls->Add(tvwCountries);
}

This would produce

Countries Statistics

Using the same approach, you can create as many branches and their child nodes as you wish. Here is an example:

void InitializeComponent()
{
        Text = "Countries Statistics";
        Size = System::Drawing::Size(242, 320);

        tvwCountries = gcnew TreeView;
        tvwCountries->Location = Point(12, 12);
        tvwCountries->Width = 210;
        tvwCountries->Height = 270;

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

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

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

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

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

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

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

        Controls->Add(tvwCountries);
}

This would produce:

Countries Statistics

The Number of Child Nodes

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() member function. Its syntax is:

public:
    int GetNodeCount(bool includeSubTrees);

Here is an example:

void InitializeComponent()
{
        Text = "Countries Statistics";
        Size = System::Drawing::Size(242, 320);

        tvwCountries = gcnew TreeView;
        tvwCountries->Location = Point(12, 12);
        tvwCountries->Width = 210;
        tvwCountries->Height = 270;

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

        . . . No Change

        Controls->Add(tvwCountries);

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

This would produce:

Countries Statistics

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.

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:

void InitializeComponent()
{
        Text = "Countries Statistics";
        Size = System::Drawing::Size(242, 320);

        tvwCountries = gcnew TreeView;
        tvwCountries->Location = Point(12, 12);
        tvwCountries->Width = 210;
        tvwCountries->Height = 100;

        TreeNode ^ nodAfrica = gcnew TreeNode("Africa");
        TreeNode ^ nodAmerica = gcnew TreeNode("America");
        TreeNode ^ nodEurope = gcnew TreeNode("Europe");
        array<TreeNode ^> ^ nodContinents = { nodAfrica, nodAmerica, nodEurope };

        TreeNode ^ nodWorld = gcnew TreeNode("World", nodContinents);
        tvwCountries->Nodes->Add(nodWorld);

        tvwCountries->SelectedNode = nodAmerica;

        Controls->Add(tvwCountries);
}

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

Countries Statistics

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.

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() member function. 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() member function. Its syntax is:

public:
    void EndEdit(bool cancel);

Just before this member function, 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() member function 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() member function 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() member function. Its syntax is:

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

The first argument to this member function 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:

void InitializeComponent()
{
        Text = "Countries Statistics";
        Size = System::Drawing::Size(242, 320);

        tvwCountries = gcnew TreeView;
        tvwCountries->Location = Point(12, 12);
        tvwCountries->Width = 210;
        tvwCountries->Height = 100;

        array<TreeNode ^> ^ nodContinents =
        {
            gcnew TreeNode("Africa"),
            gcnew TreeNode("America"),
            gcnew TreeNode("Asia"),
            gcnew TreeNode("Europe")
        };

        TreeNode ^ nodWorld = gcnew TreeNode("World", nodContinents);
        tvwCountries->Nodes->Add(nodWorld);

        tvwCountries->Nodes->Insert(1, gcnew TreeNode("Neptune"));

        Controls->Add(tvwCountries);
}

This would produce:

Countries Statistics

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

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

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

void InitializeComponent()
{
        Text = "Countries Statistics";
        Size = System::Drawing::Size(242, 320);

        tvwCountries = gcnew TreeView;
        tvwCountries->Location = Point(12, 12);
        tvwCountries->Width = 210;
        tvwCountries->Height = 100;

        array<TreeNode ^> ^ nodContinents =
        {
            gcnew TreeNode("Africa"),
            gcnew TreeNode("America"),
            gcnew TreeNode("Asia"),
            gcnew TreeNode("Europe")
        };

        TreeNode ^ nodWorld = gcnew TreeNode("World", nodContinents);
        tvwCountries->Nodes->Add(nodWorld);

        tvwCountries->ExpandAll();
        TreeNode ^ nodBranch = tvwCountries->GetNodeAt(22, 48);

        Controls->Add(tvwCountries);
        Text = nodBranch->Text;
}

This would produce:

Countries Statistics

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:

void InitializeComponent()
{
        Text = "Countries Statistics";
        Size = System::Drawing::Size(242, 320);

        tvwCountries = gcnew TreeView;
        tvwCountries->Location = Point(12, 12);
        tvwCountries->Width = 210;
        tvwCountries->Height = 100;

        array<TreeNode ^> ^ nodContinents = { gcnew TreeNode("Africa"),
				              gcnew TreeNode("America"),
				              gcnew TreeNode("Asia"),
				              gcnew TreeNode("Europe") };

        TreeNode ^ nodWorld = gcnew TreeNode("World", nodContinents);
        tvwCountries->Nodes->Add(nodWorld);

        TreeNode ^ nodFirst = tvwCountries->Nodes[0]->FirstNode;
        Controls->Add(tvwCountries);

        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() member function. Its syntax is:

public:
    bool Contains(TreeNode^ node);

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

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() member function. Its syntax is:

public:
    void Remove(TreeNode ^ node);

This member function 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() member function. Its syntax is:

public:
    virtual void RemoveAt(int index);

When calling this member function, 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() member function. 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() member functions 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() member function. Its syntax is:

public:
    virtual void Clear();

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

Characteristics of a Tree View

 

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.

Hot Tracking

In order to select an item, the user must click it or navigate to it using the keyboard. Alternatively, 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:

void InitializeComponent()
{
    Text = "Countries Statistics";
    Size = System::Drawing::Size(242, 320);

    tvwCountries = gcnew TreeView;
    tvwCountries->Location = Point(12, 12);
    tvwCountries->Width = 210;
    tvwCountries->Height = 100;

    tvwCountries->HotTracking = true;

    Controls->Add(tvwCountries);

    array<TreeNode ^> ^ nodContinents = { gcnew TreeNode("Africa"),
	 	 	 	          gcnew TreeNode("America"),
				          gcnew TreeNode("Asia"),
				          gcnew TreeNode("Europe") };

    TreeNode ^ nodWorld = gcnew TreeNode("World", nodContinents);
    tvwCountries->Nodes->Add(nodWorld);
}

This would produce:

Countries Statistics

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 of 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 (in the .NET Framework, some other libraries have it set by default to false). If this property is set to false, the lines between the nodes would not display. Here is an example:

void InitializeComponent()
{
        Text = "Countries Statistics";
        Size = System::Drawing::Size(242, 320);

        tvwCountries = gcnew TreeView;
        tvwCountries->Location = Point(12, 12);
        tvwCountries->Width = 210;
        tvwCountries->Height = 100;

        tvwCountries->ShowLines = false;

        array<TreeNode ^> ^ nodContinents = { gcnew TreeNode("Africa"),
				   gcnew TreeNode("America"),
				   gcnew TreeNode("Asia"),
				   gcnew TreeNode("Europe") };

        TreeNode ^ nodWorld = gcnew TreeNode("World", nodContinents);
        tvwCountries->Nodes->Add(nodWorld);

        Controls->Add(tvwCountries);
}

This would produce:

Countries Statistics

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:

Countries Statistics

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:

void InitializeComponent()
{
        Text = "Countries Statistics";
        Size = System::Drawing::Size(242, 320);

        tvwCountries = gcnew TreeView;
        tvwCountries->Location = Point(12, 12);
        tvwCountries->Width = 210;
        tvwCountries->Height = 100;

        tvwCountries->HotTracking = true;
        tvwCountries->ShowLines = false;
        tvwCountries->FullRowSelect = true;

        array<TreeNode ^> ^ nodContinents = { gcnew TreeNode("Africa"),
				   gcnew TreeNode("America"),
				   gcnew TreeNode("Asia"),
				   gcnew TreeNode("Europe") };

        TreeNode ^ nodWorld = gcnew TreeNode("World", nodContinents);
        tvwCountries->Nodes->Add(nodWorld);

        Controls->Add(tvwCountries);
}

This would produce:

Countries Statistics

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() member function. Its syntax is:

public:
    void Expand();

This member function 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() member function. 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() member function. 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() member function 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() member function. 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:

void InitializeComponent()
{
        Text = "Countries Statistics";
        Size = System::Drawing::Size(242, 320);

        tvwCountries = gcnew TreeView;
        tvwCountries->Location = Point(12, 12);
        tvwCountries->Width = 210;
        tvwCountries->Height = 100;

        tvwCountries->CheckBoxes = true;

        array<TreeNode ^> ^ nodContinents = { gcnew TreeNode("Africa"),
				   gcnew TreeNode("America"),
				   gcnew TreeNode("Asia"),
				   gcnew TreeNode("Europe") };

        TreeNode ^ nodWorld = gcnew TreeNode("World", nodContinents);
        tvwCountries->Nodes->Add(nodWorld);

        Controls->Add(tvwCountries);
}

This would produce:

Countries Statistics

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,
    	     array<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() member function. In the same way, you can create an array of TreeNode objects and pass it to the TreeNodeCollection::AddRange() member function.

 
 
   
 

Home Copyright © 2011 FunctionX, Inc. Home