Click here to Skip to main content
16,018,653 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 45.1K   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 
Here is an easier way: (VB.Net Code)

Private Sub TreeView1_AfterCheck(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterCheck

If e.Node.Checked = True Then
'Uncheck previous checked and selected node
Try
TreeView1.SelectedNode.Checked = False
TreeView1.SelectedNode = Nothing
Catch ex As Exception

End Try
TreeView1.SelectedNode = e.Node

Else
TreeView1.SelectedNode = Nothing

End Sub

This will Select the node on Node Check, and as any other node is checked, earlier node will be de-selected
-Ashish Agrawal

GeneralThis code will uncheck all 'ancestor' nodes of a given TreeN... Pin
BillWoodruff22-Aug-11 14:52
professionalBillWoodruff22-Aug-11 14:52 

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.