How can I find out if the selected node is a child node or a parent node in the TreeView
control?
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 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.");
}
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.");
}