C# WinForms: I need the right mouse click to select a TreeView node

I have a working TreeView and context menu which comes up when the right mouse button is clicked on various nodes and node types.  Fine.

But, if I click on a node which is not selected, the context menu pops open but the selection jumps back to the previously selected node.  This is errant behavior I need to fix.

I want the right click to select that node.

Any suggestions?

I would think this would work:

        internal void TvMainMouseUp(MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                _view.TreeViewRules.SelectedNode = _view.TreeViewRules.GetNodeAt(_view.TreeViewRules.PointToClient(Cursor.Position));
            }
        }

but it doesn't
newbiewebSr. Software EngineerAsked:
Who is Participating?
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Set it in the Opening() event of your ContextMenuStrip:
        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            TvMain.SelectedNode = TvMain.GetNodeAt(TvMain.PointToClient(Cursor.Position));
        }

Open in new window

0
 
newbiewebSr. Software EngineerAuthor Commented:
That sounds believable enough.

Thanks!
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Haha!...I tested it first.  ...but that was a simple case scenario.  Let me know if it doesn't work for any reason...
0
 
newbiewebSr. Software EngineerAuthor Commented:
ok
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.