How to make Treeview check only one option

10,414

Solution 1

The simplest way to do that is to set an even handler to your tree view's AfterCheck event. In this handler you can uncheck all the nodes but the one which just became checked:

void node_AfterCheck(object sender, TreeViewEventArgs e) {
    // only do it if the node became checked:
    if (e.Node.Checked) {
        // for all the nodes in the tree...
        foreach (TreeNode cur_node in e.Node.TreeView.Nodes) {
            // ... which are not the freshly checked one...
            if (cur_node != e.Node) {
                // ... uncheck them
                cur_node.Checked = false;
            }
        }
    }
}

Should work (didn't try)

Solution 2

It is an old post, though none of provided solutions is working in my case.

So I did as follows,

private TreeNode uncheck_treeview(TreeView treeView, TreeNode treeNode, TreeViewEventHandler e)
{
    treeView.AfterCheck -= e;

    foreach (TreeNode node in treeView.Nodes)
    {
        uncheck_treenode_tree(node);
    }

    if (treeNode != null)
    {
        treeNode.Checked = true;
    }

    treeView.AfterCheck += e;

    return treeNode;
}

and

private void uncheck_treenode(TreeNode treeNode)
{
    treeNode.Checked = false;
    foreach (TreeNode node in treeNode.Nodes)
    {
        uncheck_treenode_tree(node);
    }
}

and

private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
    var checkedNode = uncheck_treeview_tree((TreeView) sender, e.Node, treeView1_AfterCheck);
    // further processing ...
}

note that this method prevents StackOverflowException !

hope useful to others

Share:
10,414
Mr.Rendezvous
Author by

Mr.Rendezvous

back to .net project implementation. Done doing php Laravel thing. Last project is Android project. my basic is web developing. before stuff is c# winform project.

Updated on June 04, 2022

Comments

  • Mr.Rendezvous
    Mr.Rendezvous almost 2 years

    I have a treeview and Checkbox is set true. What I want is that only one checkbox is selected in the whole treeview. How can I do that?

    FYI: the treeview is in three level depth.

  • Mr.Rendezvous
    Mr.Rendezvous over 12 years
    After I try, it's only work in first level of node. it's children node not getting unchecked. cmiiw
  • SaguiItay
    SaguiItay over 12 years
    Instead of just iterating over the nodes in the TreeView, you need to recursively iterate over ALL the nodes, and uncheck them.... Notice that this is going to be slow in case your TreeView has A LOT of nodes....
  • Daryl
    Daryl over 5 years
    This is a winform question, your answer is for an ASP.Net Control.
  • Romil Kumar Jain
    Romil Kumar Jain almost 5 years
    Answer is required for winform.
  • Admin
    Admin over 2 years
    Please add further details to expand on your answer, such as working code or documentation citations.