How can I right click to select a node in a treeview control

18,674

Solution 1

That's because the highlight color performs two duties, it shows the selected node and shows the focused node. If you don't do anything with the right-click event then it jumps back to the selected node. The workaround is to select the node:

    private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {
        if (e.Button == MouseButtons.Right) treeView1.SelectedNode = e.Node;
    }

Plus anything else you want to do, usually displaying a context menu.

Solution 2

Apologies I jumped the gun slightly I found how to do this as follows:

    Private Sub TreeView1_NodeMouseClick(sender As Object, e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles TreeView1.NodeMouseClick
        If e.Button = Windows.Forms.MouseButtons.Right Then
            TreeView1.SelectedNode = e.Node
        End If
    End Sub

Shouldn't the control do this as standard though?

Share:
18,674
Matt Wilko
Author by

Matt Wilko

My areas are mainly VB.NET, ASP.NET and VB6. If you code in VB.NET you should switch Option Strict On Now My pet hate is that coding in C# doesn't give the same user experience as coding in VB.NET like: Always automatically indenting code IntelliSense that works on Enums Having to add () to the end of methods Having to use a semi-colon at the end of each line

Updated on June 05, 2022

Comments

  • Matt Wilko
    Matt Wilko about 2 years

    Why I right click on a node in my treeview the focus moves to this node and then immediately back to the previously selected node. Is there some way that I can allow the right click to select the node?