Reputation: 1853
How do I check if an item is selected in a TreeView?
I want to check if anything is selected, not a specific item.
Upvotes: 3
Views: 18116
Reputation: 53595
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;
Upvotes: 3
Reputation: 2211
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.
Upvotes: 9