How can I find out if the selected node is a child node or a parent node in the TreeView
control?
The Node. contains() method is used to check if a given node is the descendant of another node at any level. The descendant may be directly the child's parent or further up the chain. It returns a boolean value of the result.
Solution 1 Use TreeView. SelectedNode[^] property, which get or set selected node for currently selected Treeview. If no TreeNode is currently selected, the SelectedNode property is a null reference (Nothing in Visual Basic).
Approach: Write a recursive function that takes the current node and its parent as the arguments (root node is passed with -1 as its parent). If the current node is equal to the required node then print its parent and return else call the function recursively for its children and the current node as the parent.
Any subnode of a given node is called a child node, and the given node, in turn, is the child's parent. Sibling nodes are nodes on the same hierarchical level under the same parent node. Nodes higher than a given node in the same lineage are ancestors and those below it are descendants.
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.");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With