How can I determine if the selected node is a child or parent node in TreeView?

Priyanka picture Priyanka · Apr 16, 2011 · Viewed 52.8k times · Source

How can I find out if the selected node is a child node or a parent node in the TreeView control?

Answer

Cody Gray picture Cody Gray · Apr 16, 2011

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:

  1. The Nodes property returns the collection of TreeNode objects 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.");
    }
    
  2. To obtain more information, you can also examine the value of the Parent property. 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.");
    }