Click here to Skip to main content
15,891,674 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

Select only one node in Treeview

Rate me:
Please Sign up or sign in to vote.
3.75/5 (4 votes)
21 Aug 2011CPOL 44.3K   5   3
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)


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

Comments and Discussions

 
BugNot working code Pin
Martin Křížek6-Jan-16 3:00
Martin Křížek6-Jan-16 3:00 
SuggestionFor checking Single node at a time in entire tree Pin
AshishAgrawal12326-Aug-14 20:21
AshishAgrawal12326-Aug-14 20:21 
GeneralThis code will uncheck all 'ancestor' nodes of a given TreeN... Pin
BillWoodruff22-Aug-11 14:52
professionalBillWoodruff22-Aug-11 14:52 
This code will uncheck all 'ancestor' nodes of a given TreeNode, and it will uncheck all 'child' nodes of a given TreeNode; it will allow any nodes which are 'siblings' of the given TreeNode that are checked to remain checked.

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.