Home Ask Login Register

Developers Planet

Your answer is one click away!

Saber Jalilzadeh February 2016

How to deactiveating Treeview's CheckBox

I have a two treeview with some nodes which there are check-boxes behind them by using the required command. Now I want to make some nodes gray/deative. To do so, I pick one node from first treeview and then in the other treeview all nodes that their node.Text are not equal with its text would be gray. I did it by the following function:

public void deactive_checkboxs(object sender, EventArgs e)
    TreeNodeCollection nodes_checked1 = treeView1.Nodes[0].LastNode.Nodes;
    TreeNodeCollection nodes_checked2 = treeView2.Nodes[0].LastNode.Nodes;

    foreach (TreeNode node1 in nodes_checked1)
        if (node1.Checked)
            foreach (TreeNode node2 in nodes_checked2)
                if (node1.Text.Equals(node2.Text))
                    node2.Checked = false;
                    node2.Checked = false;

Of course this is not going to gray nodes rather would remove checked boxes behind the nodes( If you let me to know the making gray methods I would really appreciate it).

Now I do not know where should I put this function to have effect on the code. Does anyone help me?


TaW February 2016

This is not possible by simply setting a property.

You can neither disable a single Node nor remove its CheckBox.

Here is what you can do:

  • You can change the ForeColor of each Node individually
  • You can prevent changing the Checked state of any Node individually

Here is an example:

enter image description here

    treeView1.CheckBoxes = true;
    TreeNode tn = new TreeNode("Node 1");
    TreeNode tn1 = new TreeNode("Node 11");
    TreeNode tn2 = new TreeNode("Node 12");
    tn1.Checked = true;
    tn2.Checked = true;

    // gray text:
    tn2.ForeColor = Color.Gray;

    // mark one node somehow:
    tn2.Tag = "X";
    // cancel changes for marked node:
    treeView1.BeforeCheck += (s, e) 
        => { if (e.Node.Tag != null && e.Node.Tag.ToString() == "X") e.Cancel = true; };

To enable/disable a Node best use a function:

void SetNode(TreeNode node, bool enabled)
    node.ForeColor = enabled ? SystemColors.ControlText : Color.Gray;
    node.Tag = enabled ? null : "X";

To make the CheckBox look disabled you would have to owner-draw the node yourself. That is quite a bit of extra code..

enter image description here

First a few preparations:

    treeView1.DrawMode = TreeViewDrawMode.OwnerDrawAll;

    // cancel changes for marked node:
    treeView1.BeforeCheck += (s, e) 
        => { if (e.Node.Tag != null && e.Node.Tag.ToString() == "X") e.Cance 

Post Status

Asked in February 2016
Viewed 2,625 times
Voted 14
Answered 1 times


Leave an answer

Quote of the day: live life