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

Posted on 2012-09-13
Last Modified: 2012-09-13
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
Question by:newbieweb
    LVL 85

    Accepted Solution

    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


    Author Closing Comment

    That sounds believable enough.

    LVL 85

    Expert Comment

    by:Mike Tomlinson
    Haha!...I tested it first.  ...but that was a simple case scenario.  Let me know if it doesn't work for any reason...

    Author Comment


    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
    Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
    This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA.…

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now