Click here to Skip to main content
15,881,757 members
Articles / Desktop Programming / Win32

Simple Tri-State TreeView

Rate me:
Please Sign up or sign in to vote.
4.94/5 (28 votes)
30 Mar 2011CPOL2 min read 169K   6.8K   73   63
Provides another, simple way to get a tri-state TreeView, ensuring compatibility to all Windows UIs / styles
TriStateTreeView

Introduction

Microsoft provides a TreeView control which isn't able to display tree state checkboxes. There are many ways to implement this feature such as window proc hooking and the other stuff. This article will show you another, more simpler way using techniques provided by the .NET Framework only.

This control only inherits the original tree view control replacing CheckBoxes property usage with usage of the StateImageList and primarily overriding the node click event procedure to handle setting the tri-state.
To conform to all Windows UI styles, the state image list will be built dynamically using the CheckBoxRenderer class provided by the .NET Framework while the control is created.

Background

There may be needs to have a tree view control showing on parent nodes that check states its children aren't all the same. Further there may be needs, refreshing check states up / down the tree while checking a sub-/super-node.

Using techniques such as window proc hooking isn't the right way for everyone because it isn't always easy to debug. Further using static images would avoid displaying right checkboxes on different Windows UIs.

Using the Control / Code

Add the TriStateCheckBoxTreeView.cs to your project and simply drop the control to a form. You'll find the differences to the normal tree view control provided by the .NET Framework in the property grid. There is now a property to enable tri-state usage directly below the CheckBoxes-property.

PropertyGrid.png

Check state checking is done as normal using the Checked property from the tree node. To determine all three possible states, you may check the StateImageIndex giving the following three possible indexes:

  • 0 - Unchecked
  • 1 - Checked
  • 2 - Mixed

Rendering checkboxes using CheckBoxRenderer

C#
Bitmap GetCheckBoxBitmap(CheckBoxState myState)
{
    Bitmap bmpCheckBox = new Bitmap(16, 16);
    Graphics gfxCheckBox = Graphics.FromImage(bmpCheckBox);
    CheckBoxRenderer.DrawCheckBox(gfxCheckBox, new Point(2, 2), myState);
    gfxCheckBox.Save();
 
    return bmpCheckBox;
}

Setting the tri-state

C#
protected override void OnNodeMouseClick(TreeNodeMouseClickEventArgs e)
{
 Stack<TreeNode> stNodes;
 TreeNode tnBuffer;
 bool bMixedState;
 int iSpacing;
 int iIndex;
 
    base.OnNodeMouseClick(e);
    iSpacing = ImageList == null ? 0 : 18;			// if user clicked area
    if (e.X > e.Node.Bounds.Left - iSpacing ||		// *not* used by the state
        e.X < e.Node.Bounds.Left - (iSpacing + 16))		// image we can leave here.
    { return; }
 
    tnBuffer = e.Node;					// buffer clicked node and
    tnBuffer.Checked = !tnBuffer.Checked;			// flip its check state.
 
    stNodes = new Stack<TreeNode>(tnBuffer.Nodes.Count);	// create a new stack and
    stNodes.Push(tnBuffer);					// push buffered node first.
    do {							// let's pop node from stack,
        tnBuffer = stNodes.Pop();				// inherit buffered node's
	tnBuffer.Checked = e.Node.Checked;			// check state and push
        for (int i = 0; i < tnBuffer.Nodes.Count; i++)		// each child on the stack
            stNodes.Push(tnBuffer.Nodes[i]);			// until there is no node
    } while (stNodes.Count > 0);				// left.
			
    bMixedState = false;
    tnBuffer = e.Node;					// re-buffer clicked node.
    while (tnBuffer.Parent != null) {			// while we get a parent we
        foreach (TreeNode tnChild in tnBuffer.Parent.Nodes)	// determine mixed check states
            bMixedState |= (tnChild.Checked != tnBuffer.Checked);// and convert current check
        iIndex = (int)Convert.ToUInt32(tnBuffer.Checked);	// state to state image index.
        tnBuffer.Parent.Checked = bMixedState || (iIndex > 0);	// set parent's check state and
        if (bMixedState)					// state image in dependency
            tnBuffer.Parent.StateImageIndex = CheckBoxesTriState ? 2 : 1;
        else						// of mixed state.
            tnBuffer.Parent.StateImageIndex = iIndex;
        tnBuffer = tnBuffer.Parent;				// finally buffer parent and
    }							// loop here.
}

Limitations

This code has been written as simple as possible. There is one limitation you should keep in mind: If you're adding nodes from code you have to call control's Refresh() after adding has been completed to ensure all nodes got the right state.

History

  • 17 February 2010: First version
  • 18 February 2010: Extended sections "Introduction", "Background", "Using the control / code", fixed demo project
  • 18 March 2010: Small cosmetics to comments
  • 30 March 2011: Updated demo project

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralBug with Checked State Pin
RikTheVeggie29-Mar-11 5:31
RikTheVeggie29-Mar-11 5:31 
AnswerRe: Bug with Checked State [modified] Pin
DreamCatcher2k1029-Mar-11 6:55
DreamCatcher2k1029-Mar-11 6:55 
Questionpossible bug Pin
Mauro Luque15-Mar-11 3:13
Mauro Luque15-Mar-11 3:13 
AnswerRe: possible bug Pin
DreamCatcher2k1029-Mar-11 6:58
DreamCatcher2k1029-Mar-11 6:58 
GeneralRefresh() does not set states correctly when adding nodes from code [modified] Pin
Member 768203914-Mar-11 0:52
Member 768203914-Mar-11 0:52 
GeneralLosing state after collapse/expand Pin
DBLOOD9-Mar-11 7:31
DBLOOD9-Mar-11 7:31 
AnswerRe: Losing state after collapse/expand Pin
DreamCatcher2k109-Mar-11 8:03
DreamCatcher2k109-Mar-11 8:03 
GeneralRe: Losing state after collapse/expand Pin
DBLOOD9-Mar-11 10:49
DBLOOD9-Mar-11 10:49 
Thanks for the prompt response. That did it.
Generalproblem in setting checked status by code Pin
mahdi87_gh23-Jan-11 0:02
mahdi87_gh23-Jan-11 0:02 
GeneralRe: problem in setting checked status by code Pin
mahdi87_gh23-Jan-11 1:52
mahdi87_gh23-Jan-11 1:52 
AnswerRe: problem in setting checked status by code Pin
DreamCatcher2k1030-Mar-11 5:53
DreamCatcher2k1030-Mar-11 5:53 
GeneralThanks Pin
GuyThiebaut2-Jan-11 8:20
professionalGuyThiebaut2-Jan-11 8:20 
GeneralMy vote of 5 Pin
GuyThiebaut2-Jan-11 8:19
professionalGuyThiebaut2-Jan-11 8:19 
GeneralBug Report: Root Node Switches To Checked State Incorrectly Pin
Kivash24-Oct-10 4:13
Kivash24-Oct-10 4:13 
AnswerRe: Bug Report: Root Node Switches To Checked State Incorrectly Pin
DreamCatcher2k1026-Oct-10 23:38
DreamCatcher2k1026-Oct-10 23:38 
GeneralRe: Bug Report: Root Node Switches To Checked State Incorrectly Pin
Kivash18-Nov-10 5:50
Kivash18-Nov-10 5:50 
Questionimages are 256 color Pin
wwwings4-Oct-10 22:33
wwwings4-Oct-10 22:33 
AnswerRe: images are 256 color Pin
DreamCatcher2k1011-Oct-10 5:04
DreamCatcher2k1011-Oct-10 5:04 
Questionthe Action property of the TreeViewEventArgs Pin
saru810-Sep-10 1:05
saru810-Sep-10 1:05 
AnswerRe: the Action property of the TreeViewEventArgs Pin
DreamCatcher2k1015-Sep-10 8:27
DreamCatcher2k1015-Sep-10 8:27 
GeneralRe: the Action property of the TreeViewEventArgs Pin
saru823-Sep-10 15:03
saru823-Sep-10 15:03 
GeneralNesting Pin
m00n120-Jul-10 3:54
m00n120-Jul-10 3:54 
AnswerRe: Nesting [modified] Pin
DreamCatcher2k1020-Jul-10 3:56
DreamCatcher2k1020-Jul-10 3:56 
GeneralMy vote of 1 Pin
OrkanA15-Jun-10 10:50
OrkanA15-Jun-10 10:50 
GeneralRe: My vote of 1 Pin
DreamCatcher2k1021-Jun-10 7:56
DreamCatcher2k1021-Jun-10 7:56 

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

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