ContextMenu and TreeView in C#

28 March 2008 – 18:51

Logo .NETSince 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 ;) )

  1. 3 Responses to “ContextMenu and TreeView in C#”

  2. It is really cool

    By Ojulari HakeemNo Gravatar on Dec 16, 2008

  3. Wow … quiet easy … THX.

    By MarcNo Gravatar on Apr 29, 2009

  4. 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 CoderNo Gravatar on Aug 22, 2009

Post a Comment