Click here to Skip to main content
Click here to Skip to main content

Tri-State TreeView Control

, 2 Nov 2005 CPL
Rate this:
Please Sign up or sign in to vote.
A TreeView control with tri-state checkboxes.

Introduction

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.

Background

A tri-state 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.GetChecked(treeNode) resp. triStateTreeView.SetChecked(treeNode, checkState). Instead of a bool these methods take a CheckState.

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) == 
         TriStateTreeView.CheckState.Checked)
    DoFoo(node);
}

How does it work?

The control derives from TreeView and sets the ImageList and SelectedImageList properties for the base control. It overrides the OnClick and OnKeyDown methods.

In the OnKeyDown method, we check if the pressed key is a space, and if it is we change the state of the selected node.

The 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.

Limitations

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.

Remarks

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.

History

  • 26 March 2004 - First version.
  • 28 October 2005 - Added support for visual styles and Before/AfterCheck.

License

This article, along with any associated source code and files, is licensed under The Common Public License Version 1.0 (CPL)

Share

About the Author

Ebse
Software Developer (Senior)
Germany Germany
No Biography provided

Comments and Discussions

 
QuestionThis Post is very helpul for me Pinmemberashishgupta12125-Mar-13 9:46 
QuestionGracias Pinmemberjc2211871-Mar-13 16:08 
QuestionNot Displaying in Form Pinmemberpodal14-Dec-12 17:37 
QuestionThank you! Pinmemberkrillgar2-Mar-12 12:32 
Questionmuy bueno PinmemberMember 772271318-Nov-11 11:50 
BugRight To Left Pinmembernagham_4ng1-Aug-11 0:10 
GeneralRe: Right To Left PinmemberEbse17-Aug-11 6:20 
GeneralMy vote of 5 Pinmembervstetsko7-Mar-11 10:13 
QuestionUnusual Behavior PinmemberPhantom2081-Feb-11 7:35 
AnswerRe: Unusual Behavior PinmemberPhantom2082-Feb-11 6:55 
QuestionHow to use this dll in 64 bit mechines PinmemberMember 329057315-Sep-10 17:18 
AnswerRe: How to use this dll in 64 bit mechines PinmemberCody Tang8-Oct-10 0:30 
GeneralRe: How to use this dll in 64 bit mechines PinmemberMember 223057026-Dec-10 13:11 
GeneralRe: How to use this dll in 64 bit mechines PinmemberCody Tang30-Jul-11 22:49 
GeneralRe: How to use this dll in 64 bit mechines Pinmemberpman30-Jul-11 2:01 
GeneralImage problem PinmemberDevon Peterson17-Feb-10 13:53 
GeneralRe: Image problem PinmemberDevon Peterson17-Feb-10 14:20 
GeneralAdded ability to have disabled nodes. You might find this usefull. [modified] PinmemberMuaddubby17-Jun-09 3:49 
As noted in a previous message, I found this control extremely useful, so thx a bunch for that.

One thing I was missing, however, was the ability to enable and disable specific tree nodes. Adding an Enabled property to a derived class of the TreeNode would have been too complex because I'd have to inherit from several other classes as well and it would get messy.

Instead, I added a DisabledColor property to your TriStateTreeView. Set this property to a particular color (such as SystemColors.GrayText), and then whenever you need to disable a node, set its ForeColor to this color as well. The TriStateTreeView will then properly manage the click states of all parent and child nodes accordingly.

I can't find a way to put an attachment here, so I'm forced to paste the class.

Hope it comes in handy to someone.

[Note: the CodeProject is truncating the pasted code, as I've probably hit a maximum length or something. See my response to this note with the rest of the code.]

// ---------------------------------------------------------------------------------------------
#region // Copyright (c) 2004-2005, SIL International. All Rights Reserved.
// <copyright from='2004' to='2005' company='SIL International'>
// Copyright (c) 2004-2005, SIL International. All Rights Reserved.
//
// Distributable under the terms of either the Common Public License or the
// GNU Lesser General Public License, as specified in the LICENSING.txt file.
// </copyright>
#endregion
//
// File: TriStateTreeView.cs
// Responsibility: Eberhard Beilharz/Tim Steenwyk
//
// <remarks>
// Downloaded from the CodeProject, at http://www.codeproject.com/KB/tree/TriStateTreeViewSubmissio.aspx?msg=3054765#xx3054765xx
// </remarks>
// ---------------------------------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Runtime.Serialization;

namespace WinControls
{
/// ----------------------------------------------------------------------------------------
/// <summary>
/// A tree view with tri-state check boxes
/// </summary>
/// <remarks>
/// REVIEW: If we want to have icons in addition to the check boxes, we probably have to
/// set the icons for the check boxes in a different way. The windows tree view control
/// can have a separate image list for states.
/// </remarks>
/// ----------------------------------------------------------------------------------------
public class TriStateTreeView : TreeView
{
private System.Drawing.Color mDisabledNodeColor;

/// <summary>
/// Gets/sets the color of the disabled nodes. Used to tell if a node should be checked off or not.
/// </summary>
public System.Drawing.Color DisabledNodeColor
{
get { return mDisabledNodeColor; }
set { mDisabledNodeColor = value; }
}

private System.Windows.Forms.ImageList m_TriStateImages;
private System.ComponentModel.IContainer components;
/// <summary>
/// The check state
/// </summary>
/// <remarks>The states corresponds to image index</remarks>
public enum CheckState
{
/// <summary>greyed out</summary>
GreyChecked = 0,
/// <summary>Unchecked</summary>
Unchecked = 1,
/// <summary>Checked</summary>
Checked = 2,
}

#region Redefined Win-API structs and methods
/// <summary></summary>
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct TV_HITTESTINFO
{
/// <summary>Client coordinates of the point to test.</summary>
public Point pt;
/// <summary>Variable that receives information about the results of a hit test.</summary>
public TVHit flags;
/// <summary>Handle to the item that occupies the point.</summary>
public IntPtr hItem;
}

/// <summary>Hit tests for tree view</summary>
[Flags]
public enum TVHit
{
/// <summary>In the client area, but below the last item.</summary>
NoWhere = 0x0001,
/// <summary>On the bitmap associated with an item.</summary>
OnItemIcon = 0x0002,
/// <summary>On the label (string) associated with an item.</summary>
OnItemLabel = 0x0004,
/// <summary>In the indentation associated with an item.</summary>
OnItemIndent = 0x0008,
/// <summary>On the button associated with an item.</summary>
OnItemButton = 0x0010,
/// <summary>In the area to the right of an item. </summary>
OnItemRight = 0x0020,
/// <summary>On the state icon for a tree-view item that is in a user-defined state.</summary>
OnItemStateIcon = 0x0040,
/// <summary>On the bitmap or label associated with an item. </summary>
OnItem = (OnItemIcon | OnItemLabel | OnItemStateIcon),
/// <summary>Above the client area. </summary>
Above = 0x0100,
/// <summary>Below the client area.</summary>
Below = 0x0200,
/// <summary>To the right of the client area.</summary>
ToRight = 0x0400,
/// <summary>To the left of the client area.</summary>
ToLeft = 0x0800
}

/// <summary></summary>
public enum TreeViewMessages
{
/// <summary></summary>
TV_FIRST = 0x1100, // TreeView messages
/// <summary></summary>
TVM_HITTEST = (TV_FIRST + 17),
}

/// <summary></summary>
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int SendMessage(IntPtr hWnd, TreeViewMessages msg, int wParam, ref TV_HITTESTINFO lParam);
#endregion

#region Constructor and destructor
/// ------------------------------------------------------------------------------------
/// <summary>
/// Initializes a new instance of the <see cref="TriStateTreeView"/> class.
/// </summary>
/// ------------------------------------------------------------------------------------
public TriStateTreeView()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
mDisabledNodeColor = SystemColors.GrayText;
ImageList = m_TriStateImages;
ImageIndex = (int)CheckState.Unchecked;
SelectedImageIndex = (int)CheckState.Unchecked;
}

/// -----------------------------------------------------------------------------------
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged
/// resources; <c>false</c> to release only unmanaged resources.
/// </param>
/// -----------------------------------------------------------------------------------
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion

#region Component Designer generated code
/// -----------------------------------------------------------------------------------
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
/// -----------------------------------------------------------------------------------
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(TriStateTreeView));
this.m_TriStateImages = new System.Windows.Forms.ImageList(this.components);
//
// m_TriStateImages
//
this.m_TriStateImages.ImageSize = new System.Drawing.Size(16, 16);
this.m_TriStateImages.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("m_TriStateImages.ImageStream")));
this.m_TriStateImages.TransparentColor = System.Drawing.Color.Magenta;

}
#endregion

#region Hide no longer appropriate properties from Designer
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
[Browsable(false)]
public new bool CheckBoxes
{
get { return base.CheckBoxes; }
set { base.CheckBoxes = value; }
}

/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
[Browsable(false)]
public new int ImageIndex
{
get { return base.ImageIndex; }
set { base.ImageIndex = value; }
}

/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
[Browsable(false)]
public new ImageList ImageList
{
get { return base.ImageList; }
set { base.ImageList = value; }
}

/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// ------------------------------------------------------------------------------------
[Browsable(false)]
public new int SelectedImageIndex
{
get { return base.SelectedImageIndex; }
set { base.SelectedImageIndex = value; }
}
#endregion

#region Overrides
/*protected new TriStateTreeNode[] Nodes
{
this.nodes
}*/
/// ------------------------------------------------------------------------------------
/// <summary>
/// Called when the user clicks on an item
/// </summary>
/// <param name="e"></param>
/// ------------------------------------------------------------------------------------
protected override void OnClick(EventArgs e)
{
base.OnClick (e);

TV_HITTESTINFO hitTestInfo = new TV_HITTESTINFO();
hitTestInfo.pt = PointToClient(Control.MousePosition);

SendMessage(Handle, TreeViewMessages.TVM_HITTEST,
0, ref hitTestInfo);
if ((hitTestInfo.flags & TVHit.OnItemIcon) == TVHit.OnItemIcon)
{
TreeNode node = GetNodeAt(hitTestInfo.pt);
if (node != null)
{
ChangeNodeState(node);
}
}
}

/// ------------------------------------------------------------------------------------
/// <summary>
/// Toggle item if user presses space bar
/// </summary>
/// <param name="e"></param>
/// ------------------------------------------------------------------------------------
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown (e);

if (e.KeyCode == Keys.Space)
ChangeNodeState(SelectedNode);
}
#endregion

#region Private methods
/// ------------------------------------------------------------------------------------
/// <summary>
/// Checks or unchecks all children
/// </summary>
/// <param name="node"></param>
/// <param name="state"></param>
/// ------------------------------------------------------------------------------------
private void CheckNode(TreeNode node, CheckState state)
{
bool checkSet = InternalSetChecked(node, state);

if (checkSet)
{
foreach (TreeNode child in node.Nodes)
{
CheckNode(child, state);
}
}

ChangeParent(node.Parent);
}

/// ------------------------------------------------------------------------------------
/// <summary>
/// Called after a node changed its state. Has to go through all direct children and
/// set state based on children's state.
/// </summary>
/// <param name="node">Parent node</param>
/// ------------------------------------------------------------------------------------
private void ChangeParent(TreeNode node)
{
if (node == null)
{
return;
}

CheckState state = GetChecked(node.FirstNode);
foreach (TreeNode child in node.Nodes)
state &= GetChecked(child);

if (InternalSetChecked(node, state))
{
ChangeParent(node.Parent);
}
}

/// ------------------------------------------------------------------------------------
/// <summary>
/// Handles changing the state of a node
/// </summary>
/// <param name="node"></param>
/// ------------------------------------------------------------------------------------
protected void ChangeNodeState(TreeNode node)
{
if (node.ForeColor != mDisabledNodeColor)
{
BeginUpdate();
CheckState newState;
if (node.ImageIndex == (int)CheckState.Unchecked || node.ImageIndex < 0)
{
newState = CheckState.Checked;
}
else
{
newState = CheckState.Unchecked;
}
CheckNode(node, newState);
ChangeParent(node.Parent);
EndUpdate();
}
}

/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets the checked state of a node, but doesn't deal with children or parents
/// </summary>
/// <param name="node">Node</param>
/// <param name="state">The new checked state</param>
/// <returns><c>true</c> if checked state was set to the requested state, otherwise
/// <c>false</c>.</returns>
/// ------------------------------------------------------------------------------------
private bool InternalSetChecked(TreeNode node, CheckState state)
{
bool returnValue = true;
if (node.ForeColor != mDisabledNodeColor)
{
TreeViewCancelEventArgs args = new TreeViewCancelEventArgs(node, false, TreeViewAction.Unknown);
OnBeforeCheck(args);
if (args.Cancel)
{
returnValue = false;
}

node.ImageIndex = (int)state;
node.SelectedImageIndex = (int)state;

OnAfterCheck(new TreeViewEventArgs(node, TreeViewAction.Unknown));
}
else
{
returnValue = false;
}
return returnValue;
}

/// ------------------------------------------------------------------------------------
/// <summary>
/// Build a list of all of the tag data for checked items in the tree.
/// </summary>
/// <param name="node"></param>
/// <param name="list"></param>
/// ------------------------------------------------------------------------------------
private void BuildTagDataList(TreeNode node, ArrayList list)
{
if (GetChecked(node) == CheckState.Checked && node.Tag != null)
list.Add(node.Tag);

foreach (TreeNode child in node.Nodes)
BuildTagDataList(child, list);
}

/// ------------------------------------------------------------------------------------
/// <summary>
/// Look through the tree nodes to find the node that has given tag data and check it.
/// </summary>
/// <param name="node"></param>
/// <param name="tag"></param>
/// <param name="state"></param>
/// ------------------------------------------------------------------------------------
private void FindAndCheckNode(TreeNode node, object tag, CheckState state)
{
if (node.Tag != null && node.Tag.Equals(tag))
{
SetChecked(node, state);
return;
}

foreach (TreeNode child in node.Nodes)
FindAndCheckNode(child, tag, state);
}
#endregion

#region Public methods
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the checked state of a node
/// </summary>
/// <param name="nodeName">Node name</param>
/// <returns>The checked state</returns>
/// ------------------------------------------------------------------------------------
public CheckState GetChecked(string nodeName)
{
CheckState returnCheckState = CheckState.GreyChecked;

TreeNode[] nodes = this.Nodes.Find(nodeName, true);
if (nodes != null && nodes.Length > 0)
{
returnCheckState = GetChecked(nodes[0]);
}
else
{
throw new Exception("Node " + nodeName + " not found.");
}
return returnCheckState;
}

/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the checked state of a node
/// </summary>
/// <param name="node">Node</param>
/// <returns>The checked state</returns>
/// ------------------------------------------------------------------------------------
public CheckState GetChecked(TreeNode node)
{
if (node.ImageIndex < 0)
return CheckState.Unchecked;
else
return (CheckState)node.ImageIndex;
}

/// ------------------------------------------------------------------------------------
/// <summary>
/// Sets the checked state of a node
/// </summary>
/// <param name="node">Node</param>
/// <param name="state">The new checked state</param>
/// ------------------------------------------------------------------------------------
public void SetChecked(TreeNode node, CheckState state)
{
bool stateChanged = InternalSetChecked(node, state);

if (stateChanged)
{
CheckNode(node, state);
}
ChangeParent(node.Parent);
}

/// ------------------------------------------------------------------------------------
/// <summary>
/// Find a node in the tree that matches the given tag data and set its checked state
/// </summary>
/// <param name="tag"></param>
/// <param name="state"></param>
/// ------------------------------------------------------------------------------------
public void CheckNodeByTag(object tag, CheckState state)
{
if (tag == null)
return;
foreach (TreeNode node in Nodes)
FindAndCheckNode(node, tag, state);
}

/// ------------------------------------------------------------------------------------
/// <summary>
/// Return a list of the tag data for all of the checked items in the tree
/// </summary>
/// <returns></returns>
/// ------------------------------------------------------------------------------------
public ArrayList GetCheckedTagData()
{
ArrayList list = new ArrayList();

foreach (TreeNode node in Nodes)
BuildTagDataList(node, list);
return list;
}
#endregion
}
}


modified on Tuesday, October 13, 2009 12:07 PM

GeneralRe: Added ability to have disabled nodes. You might find this usefull. Pinmembergiova12-Oct-09 23:53 
GeneralRe: Added ability to have disabled nodes. You might find this usefull. PinmemberMuaddubby13-Oct-09 6:07 
GeneralRe: Added ability to have disabled nodes. You might find this usefull. PinmemberMuaddubby13-Oct-09 7:07 
GeneralAbsolutely awesome PinmemberMuaddubby26-May-09 4:48 
Generalcontains node! Pinmembernjuniorba7-May-09 16:07 
GeneralDisable Node Pinmemberkjward20-Apr-09 5:53 
GeneralRe: Disable Node PinmemberMuaddubby10-Jun-09 9:59 
GeneralRe: Disable Node PinmemberMuaddubby18-Jun-09 11:29 
QuestionTriStateTreeView in Oracle Forms 6i Pinmemberchrisvelarde14-Mar-09 22:14 
Generalnice work Pinmemberdrakej11-Oct-08 7:39 
Generalsuppper control... tx a lot. hat off for the author and code project Pinmemberkasunth10-Sep-08 3:56 
GeneralAwesome Control! Pinmemberkjward6-Sep-08 5:57 
QuestionError using control in VS 2005 (c#) PinmemberNIPI23-Apr-08 1:10 
GeneralThis is usable in VB as well! Pinmemberjonmach18-Nov-07 8:11 
GeneralTreeView bug Pinmembermjelten30-Jul-07 0:14 
Generalcheck box can't be displayed Pinmemberjustanumber29-Jul-07 7:21 
GeneralRe: check box can't be displayed PinmemberCodeForFun20-Sep-07 8:49 
GeneralRe: check box can't be displayed Pinmemberzz_lsl20-Dec-10 4:40 
GeneralOnBeforeCheck [modified] Pinmembermjelten19-Jul-07 23:23 
QuestionReset all to unchecked? PinmemberJim Baldwin24-Jun-07 20:30 
QuestionHow to add multiple images on same tree node? Pinmembersushantya6-Mar-07 20:39 
GeneralTri-State TreeView in Pocket Project PinmemberSilas Pereira27-Feb-07 2:08 
QuestionHow do I get what is checked? PinmemberJoppeG26-Feb-07 22:33 
AnswerArrayList Bug? PinmemberJoppeG28-Feb-07 1:55 
GeneralSolved problem PinmemberJoppeG28-Feb-07 5:07 
GeneralRe: Solved problem Pinmemberjonmach18-Nov-07 8:38 
QuestionRight-To-Left Problem Pinmembermorali2k2-Sep-06 3:58 
GeneralSimplified tree-state TreeView PinmemberLaurent Muller22-Aug-06 5:35 
GeneralRe: Simplified tree-state TreeView PinmemberUncleRedz1-Nov-06 5:18 
GeneralRe: Simplified tree-state TreeView Pinmemberbarclay19-Dec-06 12:44 
GeneralRe: Simplified tree-state TreeView Pinmemberhamlet_13-Feb-07 1:38 
GeneralRe: Simplified tree-state TreeView PinmemberMartin Welker4-Jun-07 13:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150414.1 | Last Updated 2 Nov 2005
Article Copyright 2004 by Ebse
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid