Over the last few months, I have been involved with a cople of projects that required the use of checkboxes in a TreeView control. One of the frustrations with the standard TreeView is that you can't show a partial selection to indicate that some of the children are selected. A partial selection in a complex tree allows the user to easily determine where the selections are, even if the tree is not completely expanded. A similar idea is used in manu backup programs to allow the user to select the files to be backed up.
With the current project requiring such a TreeView written in VB, I have come up with a simple solution for this problem. The attached code displays a bitmap next to the node label. Depending on the selections in the parent and children nodes, the bitmap displayed will show a checked, unchecked or partially checked box. There are also two functions to process a state change and update the nedes above and below the node which changed state.
To add this sample to your project do the following:
- Copy mod3StateTreeViewFunctions.bas and checkboxes.res to your project directory and add them to your project.
- Add an ImageList object to the form where your TreeView resides
- Initialize ImageList with tri-state checkboxes by calling InitImageList <NameOfImageList> (see Form_Load sub of the demo form)
- Bind the ImageList to your treeview
- Populate TreeView with values
- nbsp; <optional> Set checkboxes in the TreeView, updating the parents and children
To capture a state change event (see demo form for the sample code):
- Use the MouseDown event to capture the x and y location of the click.
- Use the Click event to check if the click is near the checkbox bitmap. This is tricky as the offset of nodeTest in the demo may need to be adjusted depending on the ScaleMode you use. I used Twips, the default selection.
- <optional> You may want to filter on a specific mouse button (not implemented in demo)
- <optional> Use the KeyPress event to capture keyboard ordered state change, I used space to trigger this
- If a state change is to occur, call ProcessStateChange passing the node that is about to be changed