ContextMenu and TreeView in C#
28 March 2008 – 18:51
Since a lot of time, I had a problem with the ContextMenuStrip on my application: when a user did a right-click on a node in one of my tree without having selected with left-click first, the node meant to be selected was not!
To fix that, just add this code on your tree “treeView1″ when the event “MouseDown” occurs:
private void treeView1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
TreeNode tn = treeView1.GetNodeAt(e.X, e.Y);
treeView1.SelectedNode = tn;
}
Troubles are finished for my customers! (and by extension for me as well
)

3 Responses to “ContextMenu and TreeView in C#”
It is really cool
By Ojulari Hakeem
on Dec 16, 2008
Wow … quiet easy … THX.
By Marc
on Apr 29, 2009
Hi … just wanted to drop a line saying thanks for the code chunk .. solved my null pointer bug (on context menu opening) was driving me nutz. Code gone to QA now!
Thanx lots
Regards
David
By Dave the Coder
on Aug 22, 2009