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:
The
Nodes
property returns the collection ofTreeNode
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 isnull
, then the node is at the root level of theTreeView
(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.