Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Select only one node in Treeview

3.75/5 (4 votes)
21 Aug 2011CPOL 45.2K  
Select only one node in Treeview
If you want to check Treeview control's only one node for each root node, you can use this:

C#
private void treeview1_AfterCheck(object sender, TreeViewEventArgs e)
{
    if (e.Node.Checked)
    {
        DiselectParentNodes(e.Node.Parent);
        DiselectChildNodes(e.Node.Nodes);
    }
}

private void DiselectParentNodes(TreeNode parent)
{
    while (parent != null)
    {
        if (parent.Checked)
            parent.Checked = false;
        parent = parent.Parent;
    }
}

private void DiselectChildNodes(TreeNodeCollection childes)
{
    foreach (TreeNode oneChild in childes)
    {
        if (oneChild.Checked)
            oneChild.Checked = false;
        DiselectChildNodes(oneChild.Nodes);
    }
}

License

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