开发者

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

开发者 https://www.devze.com 2023-02-26 20:42 出处:网络
How can I find out if the selected node is a child node or a parent node in the TreeView control?开发者_Go百科Exactly how you implement such a check depends on how you define \"child\" and \"parent\"

How can I find out if the selected node is a child node or a parent node in the TreeView control?开发者_Go百科


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.");
    }
    


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


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.";
   }
}


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
}


treeview.SelectedNode == null

is the best to choose.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号