Question

I'm using the click event on the TreeView to do some stuff when a node is clicked in the TreeView. I do this by getting the node that is click on by calling GetNodeAt() with the mouse coordinates, like this:

private void TreeView_Click(object sender, System.EventArgs e)
{
    MouseEventArgs mouseEventArgs = e as MouseEventArgs;

    if (mouseEventArgs == null)
        return;

    // Get the node that is being clicked.                  
    TreeNode node = this.GetNodeAt(mouseEventArgs.X, mouseEventArgs.Y);

    // Do other stuff...
}

However, the GetNodeAt() method only works when the click is on the node label, when the node image is clicked then GetNodeAt() returns null. This is a bit annoying since the node is actually selected when the image is clicked but I can't find out what node it is.

Do anyone have any suggestions?

Updated: I've gotten some suggestions to use SelectedNode instead. I can't since it's set after the Click event is fired. This actually in a control that inherits TreeView and what it does is fire it's own Clicked event but with the underlying data that the TreeNode represents instead of the TreeNode itself.

Updated: Turns out that someone had overridden the GetNodeAt() method in our code which introduced this behavior, which I didn't realize. So the question is null and void and there is no problem with the GetNodeAt() method. Why someone would do this remains a mystery. :)

Was it helpful?

Solution

Have you tried the BeforeSelect or AfterSelect Events? You can get the selected node straight from the TreeViewCancelEventArgs, then use it in your Click Event.

Edit: Additional Thought: The only problem I can see with this is that the BeforeSelect event actually fires after the Click and MouseClick Events.

Another Edit: If you need an event that fires before Click, you can use NodeMouseClick - TreeNodeMouseClickEventArgs has a Node property.

OTHER TIPS

Why not just use TreeView.SelectedNode?

Try:

TreeNode node = this.SelectedNode;

EDIT: Beaten to the punch by Sean

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top