TreeView with checkboxes implemented in the .NET Framework (property
TreeView.CheckBoxes = True) allows only 2 states (
TreeNode.Checked = True or
False). The implementation presented here:
Allows to use the state image list that is not directly available in the .NET Framework implementation.
Allows 3 states (4 including the state none) for a node: checked, unchecked, indeterminate.
Implements the logic to set the proper state of parents and children when the user changes the state of a node: it selects all children when the parent is selected, and set the state of the parent(s) to checked, unchecked or indeterminate depending on the number of children selected (all, none, etc.).
I have seen other TriState implementations in the C# section but they use the image list, not the state image list, for checkboxes and therefore doesn't allow to have icons and checkboxes for nodes at the same time.
Using the code
I have derived a
TriStateTreeView class from the base
TreeView class. This new class needs an additional state image list with icons for the 4 states: none, unchecked, checked, indeterminate (in this order).
The state image list is passed in the constructor:
m_ctlTriStateTreeView = New TriStateTreeView(Me.StateImageList)
enum type is provided to specify the state of a node:
Friend Enum CheckBoxState
None = 0
Unchecked = 1
Checked = 2
Indeterminate = 3
To add nodes to the treeview, you can use the
AddTreeNode helper function of the
objTreeNodeRoot = m_ctlTriStateTreeView.AddTreeNode( _
m_ctlTriStateTreeView.Nodes, "My Computer", _
To get the state of a node you use the
GetTreeNodeState function of the
Friend Function GetTreeNodeState(ByVal objTreeNode As _
TreeNode) As CheckBoxState
To set the state of a node you use the
SetTreeNodeState function of the
Friend Sub SetTreeNodeState(ByVal objTreeNode As _
TreeNode, ByVal eCheckBoxState As CheckBoxState)
Points of Interest
The code intercepts the
KeyUp events to change the state of a node (when clicking with the mouse or pressing space). Also, the code prevents expanding or collapsing a node double-clicking on the state image.
- 27-April-2004: Initial version.