Search code examples
vb.nettreeviewcontextmenustrip

Remove node from TreeView with ContextMenuStrip (when selection is disabled)


I have a TreeView with a node.

Selection is disabled for it with:

Private Sub TreeList_BeforeSelect(sender As Object, e As TreeViewCancelEventArgs) Handles TreeList.BeforeSelect
        e.Cancel = True
    End Sub

I was not able to find a way, to find out which node (as there will be multiple) opens the ContextMenuStrip (so I could delete it with it).

As per comments, now it works:

Dim WhichItemIsIt As TreeNode
Private Sub TreeList_NodeMouseClick(sender As Object, e As TreeNodeMouseClickEventArgs) Handles TreeList.NodeMouseClick
    WhichItemIsIt = e.Node
End Sub
Private Sub RemoveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles RemoveToolStripMenuItem.Click
    TreeList.Nodes.Remove(WhichItemIsIt)
End Sub

Solution

  • I would think that this would do the trick:

    Private lastClickedNode As TreeNode
    
    Private Sub TreeView1_NodeMouseClick(sender As Object, e As TreeNodeMouseClickEventArgs) Handles TreeView1.NodeMouseClick
        lastClickedNode = e.Node
    End Sub
    

    Right-clicking a node will assign it to that field before the menu is displayed and you can then access that node from the Click event handler of a menu item or whatever.