PrimalForms 2011: Spotlight on the TreeView Control – Part 2

November 23rd, 2011 by David Corrales
Last updated on November 23rd, 2011

 

The “Spotlight on Controls” series focuses on a single WinForms control in PrimalForms 2011, details the important Properties, Methods, and Events of the control and demonstrates how to utilize the control. Most of the information about the controls is still applicable to previous versions of PrimalForms.

In Part 1 of the Spotlight on the TreeView control, we looked at the TreeView properties, methods and event. Now we will focus on the TreeNodes and the TreeView’s Nodes property.

TreeView Nodes Property Revisited:

The TreeView keeps track of its nodes via the Nodes property, which consists of a collection of TreeNode objects.

This property can be used to remove nodes and/or add nodes to the root of the tree.

Adding Nodes:

You can add nodes via the designer or dynamically via the script editor.

Adding nodes in the designer:

Use the Property Pane to edit the nodes:

Nodes in PropertyPane

Or you can access the TreeNode Editor via the designer menu:

Nodes in Designer Menu

TreeNode Editor:

The TreeNode Editor allows you to add or remove nodes as well as alter their properties. In addition, nodes can be moved up and down the tree to become roots or child nodes.

TreeNode Editor

Adding Nodes in Script Editor:

The TreeView’s Nodes property has several methods that allow you to add nodes dynamically:

[TreeNode] Add ([string] text)

[TreeNode] Add ([TreeNode] node)

[TreeNode] Add ([string] key, [string] text)

[TreeNode] Add ([string] key, [string]text, [int] imageIndex)

[TreeNode] Add ([string] key, [string] text, [string] imageKey)

[TreeNode] Add ([string] key, [string] text, [int] imageIndex, [int] selectedImageIndex)

[TreeNode] Add ([string] key, [string] text, [string] imageKey, [string] selectedImageKey)

Example:

$buttonAddNode_Click={
    #Add and Select Node
    $treeview1.SelectedNode = $treeview1.Nodes.Add('New Node');
}

You can also use the Insert method to insert a node into a particular position:

[TreeNode] Insert ([int] index, [string] text)

[TreeNode] Insert ([int] index, [TreeNode] node)

[TreeNode] Insert ([int] index, [string] key, [string] text)

[TreeNode] Insert ([int] index, [string] key, [string] text, [int] imageIndex)

[TreeNode] Insert ([int] index, [string] key, [string] text, [string] imageKey)

[TreeNode] Insert ([int] index, [string] key, [string] text, [int] imageIndex, [int] selectedImageIndex)

[TreeNode] Insert ([int] index, [string] key, [string] text, [string] imageKey, [string] selectedImageKey)

Example:

$buttonAddNode_Click={
    #Insert node to the top of the tree
    $treeview1.Nodes.Insert(0, 'New Node');
}

All the add methods return the TreeNode which was added. Each parameter corresponds to a similarly named TreeNode property. The only exception is the Key parameter, which pertains to the Name property of the TreeNode.

TIP: When making significant changes to the TreeView’s nodes, it is recommended to use the TreeView’s BeginUpdate and  EndUpdate methods. The BeginUpdate method prevents the TreeView from redrawing every time a node is added or removed.

Example use of BeginUpdate and EndUpdate methods:

#Disable Drawing
$treeviewServices.BeginUpdate()

$services = Get-Service
$treeviewServices.Nodes.Clear()

foreach($service in $services)
{
    $node = $Root.Nodes.Add($service.DisplayName)    
}
#Enable Drawing
$treeviewServices.EndUpdate()

 

Removing Nodes:

Use the Remove method to remove any node:

[void] Remove ([TreeNode] node)

Example:

$buttonRemoveNode_Click={
    if($treeview1.SelectedNode -ne $null)
    {
        #Remove the selected node
        $treeview1.Nodes.Remove($treeview1.SelectedNode)    
    }    
}

The following method removes all the nodes in the tree:

[void] Clear ()

Example:

$buttonRemoveAllNode_Click={
    $treeview1.Nodes.Clear()
}

Searching for Nodes:

If you wish to find a node in the tree, you can use the Nodes property’s Find method:

[TreeNode []] Find ([string] key, [bool] searchAllChildren)

Example:

    $foundNodes = $treeview1.Nodes.Find("Node", $true)
    
    foreach ($node in $foundNodes) {
        Write-Host "Found: " $node.Text
    }

The Find method performs a case insensitive search of  the TreeNodes’  Name property to find a match. Therefore it is important to note that it does not search the Text property, so if the Name property is empty, the method will not find the node.

 

Let’s look at the TreeNode object and its important properties and methods:

TreeNode [System.Windows.Forms.TreeNode]

Represents a node of a TreeView.

Important Properties:

Checked

This property gets or sets a value indicating whether the tree node is in a checked state. In order to see the check box, the TreeView must have its CheckBoxes property set to True.

To determine if a Checked property has changed, use the TreeView’s AfterChecked event. The event can be useful for tracking checked nodes. Another method of determining which TreeNodes are checked is to iterate through all the TreeNodes and inspect the value of the Checked property.

Sample Function that returns all the checked nodes:

function Get-CheckedNodes 
{
    param(
    [ValidateNotNull()]
    [System.Windows.Forms.TreeNodeCollection] $NodeCollection,
    [ValidateNotNull()]
    [System.Collections.ArrayList]$CheckedNodes)
    
    foreach($Node in $NodeCollection)
    {
        if($Node.Checked)
        {
            [void]$CheckedNodes.Add($Node)
        }
        Get-CheckedNodes $Node.Nodes $CheckedNodes
    }
}

 

Calling the function:

    $CheckedNodes = New-Object System.Collections.ArrayList
    Get-CheckedNodes $treeview1.Nodes $CheckedNodes
    
    foreach($node in $CheckedNodes)
    {    
        Write-Host $node.Text
    }

 

ContextMenuStrip

This property gets or sets the shortcut menu associated with this tree node.

Use this property to assign a specific ContextMenuStrip to each individual node.  Each node can share the same ContextMenuStrip or have a unique ContextMenuStrip assigned to it.

FirstNode

This property returns the first child tree node in the tree node collection.

This property can be useful for navigating through the nodes.

FullPath

This property returns the path from the root tree node to the current tree node. This property can be useful for navigation purposes.

Example:

AfterSort

Node “1 Nodes” FullPath is: “Root\B Node\1 Node”

You can change the backslash character ‘\’ to any other character or string by changing the TreeView’s PathSeparator property.

IsEditing

This property gets a value indicating whether the tree node is in an editable state.

IsExpanded

This property gets a value indicating whether the tree node is in the expanded state.

IsSelected

This property gets a value indicating whether the tree node is in the selected state.

Name

This property gets or sets the name of the tree node.  Note: The Name property is not the same as the Text property. When using the Find method, it will use this property to perform the search.

NextNode

This property gets the next sibling tree node.

This property can be useful for navigating through the nodes.

$node = $treeView1.Nodes[0]

while($node -ne $null)
{
    Write-Host $node.Name  
    $node = $node.NextNode
}

 

Nodes

This property get the collection of child TreeNode objects assigned to the current tree node. 

This property is identical to the TreeView’s Nodes property, but instead contains this node’s children. 

PrevNode

This property gets the previous sibling tree node. 

Like the NextNode property, this property can be useful for navigating through the nodes.

ImageIndex

This property gets or sets the image list index value of the image displayed when the tree node is in the unselected state.

TreeView’s ImageList property must be set for this property to function correctly. If not set, the node will use the default index determined by the TreeView’s ImageIndex property.

To remove the Image from the node, set the node’s ImageIndex property to –1.

SelectedImageIndex

This property gets or sets the image list index value of the image that is displayed when the tree node is in the selected state.

TreeView’s ImageList property must be set for this property to function correctly. If not set, the node will use the default index determined by the TreeView’s SelectedImageIndex property.

To remove the Image from the node, set the node’s SelectedImageIndex property to –1.

StateImageIndex

This property gets or sets the index of the image that is used to indicate the state of the TreeNode when the parent TreeView has its CheckBoxes property set to false.

TreeView’s StateImageList property must be set for this property to function correctly. To remove the Image from the node, set the node’s StateImageList property to –1.

Example:

StateImageIndex

In this example the StateImageIndex is used to signify a problem with a file.

Warning: If the TreeView’s CheckBoxes is set to True, the StateImage will be displayed instead of the CheckBox. 

Tag

This property gets or sets the object that contains data about the tree node.

This property can be extremely useful for linking the Node to an actual object. By using the Tag property, you can easily reference the original object. For example, if the nodes of a TreeView consists of services and you want to start / stop a service by double clicking on the node, you can assign the service object to the node’s Tag property and as a result it simplifies the event handling.

$treeviewServices_NodeMouseDoubleClick=[System.Windows.Forms.TreeNodeMouseClickEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.TreeNodeMouseClickEventArgs]
    $service = $_.Node.Tag
    
    if($service -ne $null)#Is there is a service object?
    {
        if($service.Status -eq 'Running')
        {
            if($service.CanPauseAndContinue)
            {
                #$service.Pause()
                Write-Host 'Pause Service'
            }
            else
            {
                #$service.Stop()
                Write-Host 'Stop Service'
            }
        }
        elseif($service.Status -eq 'Paused')
        {
            #$service.Continue()
            Write-Host 'Continue Service'
        }
        else
        {
            #$service.Start()    
            Write-Host 'Start Service'
        }
    }
    
}

 

Text

This property gets or sets the text displayed in the label of the tree node.

ToolTipText

This property gets or sets the text that appears when the mouse pointer hovers over a TreeNode. The TreeView’s ShowNodeTooltips property must be set to True in order for the tooltips to display.

$node.ToolTipText = 'This node has a tooltip!' 
 

Methods:

BeginEdit

This method initiates the editing of the tree node label.

$buttonRename_Click={
    if($treeview1.SelectedNode -ne $null)
    {
        $treeview1.SelectedNode.BeginEdit()
    }
}

 

Collapse

This method collapses the TreeNode and optionally collapses its children.

#Collapse All Children
$treeview1.SelectedNode.Collapse()

#Collapse only this node and leave children
$treeview1.SelectedNode.Collapse($false)

EndEdit

This method ends the editing of the tree node label.

if($treeview1.SelectedNode.IsEditing)
{
    $treeview1.SelectedNode.EndEdit()    
}

 

EnsureVisible

This method ensures that the tree node is visible, expanding tree nodes and scrolling the tree view control as necessary.

$treeview1.SelectedNode.EnsureVisible()

Expand

This method expands the tree node.

$treeview1.SelectedNode.Expand()

ExpandAll

This method expands all the child tree nodes.

$treeview1.SelectedNode.ExpandAll()

Remove

This method removes the current tree node from the tree view control.

$treeview1.SelectedNode.Remove()

Toggle

This method toggles the tree node to either the expanded or collapsed state.

$treeview1.SelectedNode.Toggle()

 

 Download the TreeView Samples from the downloads section.

 

 
[Google+]   [Facebook]   [LinkedIn]   [StumbleUpon]   [Digg]   [Reddit]   [Google Bookmark]  

Tags: , , , ,