tags:

views:

312

answers:

2

How do I check if an item is selected in a TreeView? In C#

I want to check if anything is selected, not a specific item

+5  A: 

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.

KennyDeriemaeker
+4  A: 

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;
Jay Riggs