The TreeView Control
- Details
- Written by David Corrales
- Last Updated: 13 June 2016
- Created: 23 November 2011
- Hits: 38475
TreeView [System.Windows.Forms.TreeView]
Displays a hierarchical collection of labeled items, each of which is represented by a TreeNode.
- MSDN Page: System.Windows.Forms.TreeView
- Default Event: AfterSelect
Important Properties:
- CheckBoxes
- ContextMenuStrip
- HideSelection
- ImageList
- ImageIndex
- SelectedImageIndex
- StateImageList
- LabelEdit
- ShowLines
- ShowNodeToolTips
- ShowPlusMinus
- ShowRootLines
- Nodes
- SelectedNode
Important Methods:
Important Events:
TreeView Nodes Property In-Depth:
Why use a TreeView control?
When it comes to displaying hierarchical information such as a folder structure, the TreeView control is a perfect choice. In addition, the TreeView allows users to rename tree nodes which can be useful in many instances. The TreeView also serves as a good navigation tool.
Important Properties:
CheckBoxes
This property indicates whether check boxes are displayed next to the tree nodes in the tree view control.
This property can be useful if you want the user to pick multiple nodes by checking them. Note: Checked nodes are not treated as if they are “selected”. We will cover how to determine which nodes are checked by the user later in this article.
Default Value: False
ContextMenuStrip
This property sets the shortcut menu associated with the control.
Use this property to select an existing ContextMenuStrip.The ContextMenuStrip is featured in another Spotlight on Control article. The context menu will appear when TreeView is right clicked. Adding specific context menus for nodes is covered later in this article.
HideSelection
This property indicates whether the selected tree node remains highlighted even when the tree view has lost the focus such as when another control is selected.
Default Value: True
Selection with Focus:
Selection without Focus and HideSelection is set to False:
ImageList
This property sets the ImageList that contains the Image objects that are used by the tree nodes. (See the ImageList Control article for more details.)
ImageIndex
This property indicates the default image index value that is displayed by the tree nodes.
SelectedImageIndex
This property indicates the default image index value that is displayed when a tree node is selected.
StateImageList
This property sets the ImageList that is used to indicate the state of the TreeView and its nodes. This image is displayed next to the imaged specified by the ImageIndex and SelectedImageIndex. (More details later in this article.)
LabelEdit
This property indicates whether the label text of the tree nodes can be edited. This can be useful when you wish to allow the user to rename an object such as a file.
Default Value: False
When a user edits a label, various events are called that allow you to prevent or reject the changed label. See the BeforeLabeEdit and AfterLabelEdit events before for more details.
ShowLines
This property indicates whether lines are drawn between tree nodes in the tree view control.
Default Value: True
The lines are hidden when ShowLines is set to False:
ShowNodeToolTips
This property indicates whether ToolTips are shown when the mouse pointer hovers over a TreeNode. Displaying tooltips can be helpful in providing users with hints about what the node represents.
Default Value: False
See ToolTipText under TreeNode properties to see how to set a node’s tooltip.
ShowPlusMinus
This property indicates whether plus-sign (+) and minus-sign (-) buttons are displayed next to tree nodes that contain child tree nodes.
Default Value: True
When ShowPlusMinus is set to False, the plus/minus buttons are hidden but you can still expand and collapse the node by double clicking on it. To disable this behavior please refer to the BeforeExpand / BeforeCollapse events below.
ShowRootLines
This property indicates whether lines are drawn between the tree nodes that are at the root of the tree view.
Default Value: True
When the ShowRootLines is set to False, the root node does not display either a line or the plus or minus button.
Nodes
This property contains the collection of tree nodes that are assigned to the tree view control.
Use this property to add or remove nodes. We will examine this property in more detail later in the article.
SelectedNode
This property get or sets the tree node that is currently selected in the tree view control.
Example of how to select the first root node via Script Editor:
$treeview1.SelectedNode = $treeview1.Nodes[0]
Important Methods:
CollapseAll
This method collapses all the tree nodes.
$treeview1.CollapseAll()
ExpandAll
This method expands all the tree nodes.
$treeview1.ExpandAll()
Sort
This method sorts all the nodes in TreeView control.
$treeview1.Sort()
Before Sort:
After Sort:
Important Events:
After Events:
The ‘After’ events listed below, except AfterLabelEdit, have the following as an argument that is accessible via the $_ variable:
[System.Windows.Forms.TreeViewEventArgs]
Properties | |
Action | Gets the type of action that raised the event.
Values: Unknown ByKeyboard ByMouse Collapse Expand |
Node | Gets the tree node that has been checked, expanded, collapsed, or selected. |
AfterCheck
This event occurs after the tree node check box is checked or unchecked.
AfterCollapse
This event occurs after the tree node is collapsed.
AfterExpand
This event occurs after the tree node is expanded.
AfterLabelEdit
This event occurs after the tree node label text is edited. Label editing must be enabled for this event to be called (See LabelEdit property).
AfterLabelEdit event uses the following argument:
[System.Windows.Forms.NodeLabelEditEventArgs]
Properties | |
CancelEdit | Gets or sets a value indicating whether the edit has been canceled. |
Label | Gets the new text to associate with the tree node. |
Node | Gets the tree node that has been checked, expanded, collapsed, or selected. |
Use this event to react to name changes. For example if the Node represents a file, you can use this event as a trigger for renaming the file. You should also perform any validation and reject the name change if there is a failure.
$treeview1_AfterLabelEdit=[System.Windows.Forms.NodeLabelEditEventHandler]{ #Event Argument: $_ = [System.Windows.Forms.NodeLabelEditEventArgs] if(-not (Validate-FileName $_.Label)) { $_.CancelEdit = $true } else { #Rename the file } }
AfterSelect
This event occurs after the tree node is selected.
This event is useful if you are using the TreeView as a form of navigation.
$treeview1_AfterSelect=[System.Windows.Forms.TreeViewEventHandler]{ #Event Argument: $_ = [System.Windows.Forms.TreeViewEventArgs] Write-Host 'Node Selected: ' $_.Node.Text }
Before Events:
The ‘Before’ events listed below, except BeforeLabelEdit, have the following as an argument that is accessible via the $_ variable:
[System.Windows.Forms.TreeViewCancelEventArgs]
Properties | |
Action | Gets the type of action that raised the event.
Values: Unknown ByKeyboard ByMouse Collapse Expand |
Cancel | Gets or sets a value indicating whether the event should be canceled. To cancel the event, set this property to True. |
Node | Gets the tree node that has been checked, expanded, collapsed, or selected. |
BeforeCheck
This event occurs before the tree node check box is checked.
Use this event to cancel the check action:
$treeview1_BeforeCheck=[System.Windows.Forms.TreeViewCancelEventHandler]{ #Event Argument: $_ = [System.Windows.Forms.TreeViewCancelEventArgs] if($_.Node.Checked) { # Prevent node from unchecking $_.Cancel = $true } }
BeforeCollapse
This event occurs before the tree node is collapsed.
Use this event to cancel the action.
BeforeExpand
This event occurs before the tree node is expanded.
Use this event to cancel the action.
BeforeLabelEdit
This event occurs before the tree node label text is edited. Label editing must be enabled for this event to be called (See LabelEdit property).
This event uses the [System.Windows.Forms.NodeLabelEditEventArgs] argument. See AfterLabelEdit for more information about this argument.
Use this event to prevent users from renaming specific nodes.
BeforeSelect
This event occurs before the tree node is selected.
You can use this event to prevent specific nodes from being selected.
Click Events:
The ‘Click’ events have the following as an argument that is accessible via the $_ variable:
[System.Windows.Forms.TreeNodeMouseClickEventArgs]
Properties | |
Button | Gets which mouse button was pressed.
Values: Left None Right Middle |
Clicks | Gets the number of times the mouse button was pressed and released. |
Location | Gets the location of the mouse during the generating mouse event. |
Node | Gets the node that was clicked. |
NodeMouseClick
This event occurs when the user clicks a TreeNode with the mouse.
Example:
$treeview1_NodeMouseClick=[System.Windows.Forms.TreeNodeMouseClickEventHandler]{ #Event Argument: $_ = [System.Windows.Forms.TreeNodeMouseClickEventArgs] if($_.Button -eq 'Right') { Write-Host "Right Click Node: " $_.Node.Text $this.SelectedNode = $_.Node #Select the node (Helpful when using a ContextMenuStrip) } }
NodeMouseDoubleClick
Occurs when the user double-clicks a TreeNode with the mouse.
$treeview1_NodeMouseDoubleClick=[System.Windows.Forms.TreeNodeMouseClickEventHandler]{ #Event Argument: $_ = [System.Windows.Forms.TreeNodeMouseClickEventArgs] Write-Host "Double Click " $_.Node.Text }
TreeView Nodes Property In-Depth
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:
Or you can access the TreeNode Editor via the 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.
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
- ContextMenuStrip
- FirstNode
- FullPath
- IsEditing
- IsExpanded
- IsSelected
- Name
- NextNode
- Nodes
- PrevNode
- ImageIndex
- SelectedImageIndex
- StateImageIndex
- Tag
- Text
- ToolTipText
Methods:
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:
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:
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.
For licensed customers, use the forum associated with your product in our Product Support Forums for Registered Customers.
For users of trial versions, please post in our Former and Future Customers - Questions forum.