How can I find out if the selected node is a child node or a parent node in the TreeView control?
5 Answers
Exactly how you implement such a check depends on how you define "child" and "parent" nodes. But there are two properties exposed by each TreeNode object that provide important information:
- The - Nodesproperty returns the collection of- TreeNodeobjects contained by that particular node. So, by simply checking to see how many child nodes the selected node contains, you can determine whether or not it is a parent node:- if (selectedNode.Nodes.Count == 0) { MessageBox.Show("The node does not have any children."); } else { MessageBox.Show("The node has children, so it must be a parent."); }
- To obtain more information, you can also examine the value of the - Parentproperty. If this value is- null, then the node is at the root level of the- TreeView(it does not have a parent):- if (selectedNode.Parent == null) { MessageBox.Show("The node does not have a parent."); } else { MessageBox.Show("The node has a parent, so it must be a child."); }
 
    
    - 239,200
- 50
- 490
- 574
You can use the TreeNode.Parent property for this.
If its value is a null-reference,  the node is at the root level.
TreeView treeView = ...
var selectedNode = treeView.SelectedNode;
if(selectedNode ! = null)
{
    if(selectedNode.Parent == null)  
    {     
        // Root-level node  
    }
    else 
    {     
        // Child node
    } 
}
else
{
    // A node hasn't been selected.
}
 
    
    - 111,048
- 26
- 262
- 307
Try this
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{  
   Label1.Text = "";
   if(e.Node.Parent!= null && 
     e.Node.Parent.GetType() == typeof(TreeNode) )
   {
      Label1.Text = "Parent: " + e.Node.Parent.Text + "\n"
         + "Index Position: " + e.Node.Parent.Index.ToString();
   }
   else
   {
      Label1.Text = "This is parent node.";
   }
}
 
    
    - 860
- 15
- 16
For root node is the parent TreeView .. it is possible to check if we compare the types of ->
if (currentNode.Parent.GetType() == typeof(TreeView)) 
{
    // root node
}
 
    
    - 325
- 4
- 13
treeview.SelectedNode == null
is the best to choose.
 
    
    - 31
- 3
- 
                    2I don't understand how this answers the question. – JDB Oct 09 '12 at 03:41
