How to check if an item is selected in TreeView?
开发者_运维问答How do I check if an item is selected in a TreeView?
I want to check if anything is selected, not a specific item.
The TreeView class has a SelectedNode property that holds the currently selected TreeNode.
TreeNode tn = ctl_treeView.SelectedNode;
if ( tn == null )
Console.WriteLine("No tree node selected.");
else
Console.WriteLine("Selected tree node {0}.", tn.Name );
You can compare the returned TreeNode reference to the TreeNode you're looking for, and so check if it's currently selected.
To check the selected status of a specific item, you can explicitly reference the node you want to check and return its IsSelected
property. Like this:
Assuming a TreeView structured as follows:
Node0
+--- Node3
Node1
Node2
+--- Node4 **<-- **you want to check this Node****
+--- Node5
Your code could look like this:
bool isSelected = treeView1.Nodes["Node2"].Nodes["Node4"].IsSelected;
精彩评论