How do I programmatically push to a node?

I would like to programmatically emulate a click on a node in a TreeView control. There is no interactive method to see (something corresponding to other controls ) and I am guessing that I need to navigate to the currently selected node.

So, I tried the following:

christmasTreeView.SelectedNode. ???

      

However, intellisense didn't give me any hints as to what needs to be called to trigger a mouse click on a node. How can I do that?

+3


source to share


3 answers


You can do something like:

// find the node you want to select and make it the SelectedNode
christmasTreeView.SelectedNode = christmasTreeView.Nodes[1]; // <-- the index you need
// Now trigger a select
christmasTreeView.Select();
// or
//christmasTreeView.Focus();

      

This will work:



private void christmasTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
   // awesome
}

      

Possible approach (not very sleek though).

TreeNode preSelected = ChristmasTreeView.SelectedNode;
ChristmasTreeView.SelectedNode = null;
ChristmasTreeView.SelectedNode = preSelected;
ChristmasTreeView.Select();

      

+3


source


The main problem is that Windows Forms is TreeNode

not a result Control

like a TreeView

(or for example a Button

). This is much closer to the "model" class, which means that it primarily concerns the hierarchical organization of your data. Although some of the abstract abstractions leak in the properties, such as Color

, Bounds

, Handle

, etc., TreeNode

does not know how to draw themselves, and how to handle the click event.

On the other hand, a TreeView

is actual Control

, which means that you can extract from it and be able to override its protected method OnClick

, as shown in the example you linked .



If you want to follow this path, you can derive your class from it TreeView

and override the protected method OnNodeMouseClick

. This method is specific to TreeView

and is called by its method WndProc

when clicking on a certain node.

But after reading your comments on the other answers, it seems like this is not something you really need to do to achieve your goal.

+1


source


You need to use an event handler for TreeView.NodeMouseClick. This event received a parameter that you can call in your EventHandler as shown below:

void MyTreeview_NodeMouseClick(object sender,  
TreeNodeMouseClickEventArgs e)
{
// do something with e.Node
}

      

0


source







All Articles