views:

638

answers:

1

This is the same as how most apps behave. I thought TreeView worked like that by default.

Is there a way to do this, or do I have to get all the children of a TreeNode that's checked and check them myself?

This is winforms.

+3  A: 

You need to do it yourself, which on the other hand is not very hard:

private void TreeView_AfterCheck(object sender, TreeViewEventArgs e)
{
    SetChildrenChecked(e.Node, e.Node.Checked);
}

private void SetChildrenChecked(TreeNode treeNode, bool checkedState)
{
    foreach (TreeNode item in treeNode.Nodes)
    {
        item.Checked = checkedState;
    }
}

This takes care of both checking and unchecking all children (regardless of how many levels down there may be child nodes).

Update
Expanded code sample that will also check/uncheck parent node if all of its child nodes are checked or unchecked manually (not thoroughly tested, could probably be done more elegantly):

private void TreeView_AfterCheck(object sender, TreeViewEventArgs e)
{
    SetChildrenChecked(e.Node, e.Node.Checked);

    if (e.Node.Parent != null)
    {
        bool setParentChecked = true;
        foreach (TreeNode node in e.Node.Parent.Nodes)
        {
            if (node.Checked != e.Node.Checked)
            {
                setParentChecked = false;
                break;
            }
        }
        if (setParentChecked)
        {
            e.Node.Parent.Checked = e.Node.Checked;
        }
    }
}

private void SetChildrenChecked(TreeNode treeNode, bool checkedState)
{
    foreach (TreeNode item in treeNode.Nodes)
    {
        if (item.Checked != checkedState)
        {
            item.Checked = checkedState;
        }
    }
}

The if-block that is added in the SetChildrenChecked method will prevent a StackOverflowException in the case where you check a node with child nodes, they get checked, and when the last one is checked the parent (the one you clicked on) gets cecked and triggers the AfterCheck event again (which surprises me a bit; I would not expect the event to be raised when the Checked property value does not change but rather just gets assigned the same value it already had, but then again the event is called AfterCheck, not AfterCheckedChanged).

Fredrik Mörk
Thanks I will try this and mark as an answer.
Joan Venge
Does this also check a node if a user manually checks all child nodes?
dtb
@dtb: no, it does not trigger upwards. Good point. Will update the answer.
Fredrik Mörk
Actually what about the case if the user checks a parent node, and then unchecks a children, then the parent node is checked differently to show that its children aren't all checked?
Joan Venge
@Joan: AFAIK the TreeView does not support that intermediate checked state natively. This can be achieved by playing with the tree node icons (use images instead of the checkboxes to visualize checked state). This requires more coding though.
Fredrik Mörk
Thanks Fredrick, I didn't know that.
Joan Venge