Microsoft provides a
TreeView control in the .NET framework, but as usual it doesn't expose all the functionality that the underlying common control provides. It has the possibility to display check-boxes but they can't be tri-state check boxes.
This control adds tri-state check boxes and the necessary handling methods to check/uncheck all sub-items if the user clicks on a node, as well as displays a grey-checked check box for the parent if the siblings have differing check/uncheck states.
TreeView is a tree view control that displays check boxes next to the tree nodes. If you click on a check box, it checks (or unchecks) the check box and all sub-nodes.
If the nodes on the same level as the clicked node have differing check states the parent node's check box is grey-checked as well as its parent's and so on.
If you click on a grey-checked check box it unchecks that node and all its subnodes.
How to use the control
Add TriStateTreeView.cs to your project and then simply drop the
TriStateTreeView control on a form and use it as a regular
TreeView control. The only difference is when you want to access the checked state of a node. Instead of using the
treeNode.Checked property you call
triStateTreeView.SetChecked(treeNode, checkState). Instead of a
bool these methods take a
For example, the following code snippet checks the state of all the top level nodes:
foreach (TreeNode node in m_treeView.Nodes)
if (m_treeView.GetChecked(node) ==
How does it work?
The control derives from
TreeView and sets the
SelectedImageList properties for the base control. It overrides the
OnKeyDown method, we check if the pressed key is a space, and if it is we change the state of the selected node.
OnClick method is a little trickier. We have to use the
TVM_HITTEST Win32 API message to determine if the user clicked on the icon or on the item. If the user clicked on the icon we change the state of the selected node.
This control doesn't support displaying both check boxes and icons. If you need this functionality you have to call additional Win32 API methods. The common control tree view control supports having multiple image lists, but this functionality isn't exposed in .NET.
The control makes use of the Skybound.VisualStyle assembly from www.skybound.ca. By commenting out the lines that reference that assembly it will easily work without it. Another way of making the control aware of visual styles is described here.
The demo project consists of an assembly that contains the
TriStateTreeView, a demo project and a NUnit test assembly with some tests for the control.
- 26 March 2004 - First version.
- 28 October 2005 - Added support for visual styles and