Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically click a TreeView TreeNode so it appears highlighted in the list and fires the AfterSelect event?

I have a TreeView control in a Winforms app, and basically the objective is to display a form that contains a TreeView control, and I want to display the form with a node opened (easy - EnsureVisible) and selected.

The problem that I'm running into is that when I set the TreeView control's SelectedNode property, the node isn't highlighted and the AfterSelect event isn't firing as I would expect it to. The AfterSelect thing is easy to code around, but the lack of highlighting is annoying.

like image 497
ThomW Avatar asked May 08 '09 17:05

ThomW


People also ask

How do I know if TreeView node is selected?

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.

How do I get data from TreeView database?

Populating TreeView from database Inside the PopulateTreeView method, a loop is executed over the DataTable and if the ParentId is 0 i.e. the node is a parent node, a query is executed over the VehicleSubTypes table to populate the corresponding child nodes and again the PopulateTreeView method is called.

How do you select a node in TreeView vb net?

Selected = true; The node for which the property is set gets selected as shown below. Furthermore, you can also select a node at runtime by right-clicking it. This is the default behavior of TreeView.


2 Answers

The easiest way to programmatically do this (that I have found) is to fake the click event. I needed to do this as when I searched for a node using TreeView.Nodes.Find(), I needed it to click each level of the hierarchy on the way down. So I basically did the following:

tvMyTreeView_NodeMouseClick(tvMyTreeView, new TreeNodeMouseClickEventArgs(myNode, MouseButtons.Left, 1, 0, 0));

Which fired my event and faking a left single click on the myNode node. Inside that event you can format e.Node however you would want to colourise it. Hope this helps.

like image 62
Darren Quinn Avatar answered Oct 23 '22 20:10

Darren Quinn


Is it because the TreeView doesn't have focus? Does setting the TreeView's HideSelection property to False change the behavior you're seeing?

like image 27
great_llama Avatar answered Oct 23 '22 21:10

great_llama