1

I want to set the selected node to nothing if a user clicks on the treeview (right or left) and the cursor is not on a node. I thought the TreeView.MouseClick event would fire if any part of the control was clicked, but it seems only to fire when a node is clicked. Is there any way to do this?

Edit* I do know how to set the selected node to nothing, tvwMain.SelectedNode = Nothing but am unable to do so when the control is clicked and there is no node at that point as the TreeView.MouseClick and TreeView.Click events do not seem to fire unless a node is clicked.

Private Sub tvwMain_NodeMouseClick(sender As Object, e As MouseEventArgs) Handles tvwMain.Click
    Dim p = New Point(e.X, e.Y)
    Dim node As TreeNode = tvwMain.GetNodeAt(p)

    If node IsNot Nothing Then
        tvwMain.SelectedNode = node
        MsgBox("HERE")
    Else
        tvwMain.SelectedNode = Nothing
        MsgBox("TOO")
    End If
End Sub
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
Alex
  • 509
  • 1
  • 11
  • 26
  • Winforms, WPF or ASP.Net? – Jeremy Thompson Jul 18 '16 at 00:42
  • Possible duplicate of [How do I clear the selection of a selected node in a TreeView?](http://stackoverflow.com/questions/11824443/how-do-i-clear-the-selection-of-a-selected-node-in-a-treeview) – Jeremy Thompson Jul 18 '16 at 00:44
  • I can set the selected node to nothing, `tvwMain.SelectedNode = Nothing` but I want to do that when the user clicks on the control, but there is no node under the click. Also, WinForms – Alex Jul 18 '16 at 00:46
  • `Click` and `MouseClick` should work since they're just inherited from `Control`. There is even a `NodeMouseClick` event which should go for nodes only. – Visual Vincent Jul 18 '16 at 09:55

1 Answers1

1
TreeNode test = tvwMain.GetNodeAt(tvwMain.PointToClient(Cursor.Position))
If IsNothing(test) Then tvwMain.SelectedNode = Nothing
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
  • I had a method similar to this (Added above) But had the same issue that the events were not firing, – Alex Jul 18 '16 at 01:16
  • 1
    If the .Click, .MouseClick, NodeMouseClick events dont fire unless the cursor is over a node then use one of the other events like MouseDown or Hover: https://msdn.microsoft.com/en-us/library/system.windows.forms.treeview_events(v=vs.110).aspx – Jeremy Thompson Jul 18 '16 at 01:32