Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 223
Priyanka Avatar asked Apr 16 '11 05:04

Priyanka


People also ask

How do you check if a node is a parent?

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.

How do I know if TreeView node is selected?

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).

How do you find the parent of nodes in a tree?

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.

What are parent nodes and child nodes?

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.


1 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:

  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.");
    }
    
like image 128
Cody Gray Avatar answered Sep 25 '22 14:09

Cody Gray