Problem:
There is a TreeView control with n number of nodes. When the user right clicks on the TreeView control, get the node on which the right click was performed.
Background:
In TreeView control, SelectedNode property is set whenever left click occurs. This is not true for right clicks. So, we need to have some workaround for this.
Solution 1:
The most popular solution is to handle the MouseDown event. Check if the click was a right click and then use the TreeView control’s GetNodeAt API to get the node which was clicked at.
private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
TreeNode selectedNode = treeView1.GetNodeAt(e.X, e.Y);
MessageBox.Show("You clicked on node: " + selectedNode.Text);
}
}
Solution 2:
Handle the NodeMouseClick event. The TreeNodeMouseClickEventArgs has the node which was clicked at.
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
MessageBox.Show("You clicked on node: " + e.Node.Text, "Solution 2");
}
}
SelectedNode property of a treeview is set whenever a left click occurs. Why can’t the same be applied for right click? Right click on a treeview is such a common UI event, that users will benefit from it.

December 9, 2007 at 10:04 am
Excellent explanation and solutions. I wish Microsoft would just make a NodeMouseRightClick() event but until they do, this is the next best thing.
March 4, 2008 at 4:00 pm
“SelectedNode property of a treeview is set whenever a left click occurs. Why can’t the same be applied for right click?”
This would cause an inconsistency for instance when you display a context menu and the user cancels the menu.
December 1, 2008 at 3:37 pm
I need to thank you very much and need to tell you that I’m use this code to select not in right and left click
Me.TreeView1.SelectedNode = e.Node
December 5, 2008 at 6:26 pm
Excellent !! Thank you.
January 23, 2009 at 10:40 pm
we simply need to handle the NodeMouseClickEvent.
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
this.treeView1.SelectedNode = e.Node;
}
}
March 3, 2009 at 8:10 pm
Hello webmaster
I would like to share with you a link to your site
write me here preonrelt@mail.ru