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.
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.
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.
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.
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.
Is it because the TreeView doesn't have focus? Does setting the TreeView's HideSelection property to False change the behavior you're seeing?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With