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

╄→尐↘猪︶ㄣ 提交于 2019-12-04 15:55:43

问题


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


回答1:


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



回答2:


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



回答3:


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



回答4:


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
}



回答5:


treeview.SelectedNode == null

is the best to choose.



来源:https://stackoverflow.com/questions/5684781/how-can-i-determine-if-the-selected-node-is-a-child-or-parent-node-in-treeview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!