newbie: removing node from treeview

  • Thread starter Thread starter Christy Davids
  • Start date Start date
C

Christy Davids

This must really be a stupid question, but after banging
my head against it for a few hours I'll just have to ask
it.

I've got a context menu attached to a treeview with a menu
item for deleting a node in the treeview. The code for
the menu item click event is as follows:

Private Sub MenuItemDelete_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
MenuItemDelete.Click
Dim tvn As TreeNode = TreeView1.SelectedNode
tvn.Remove()
End Sub

This produces an "Object reference not set to an instance
of an object" error at the tvn.Remove(). Walking through
it in the debugger I can see that tvn is being set with
all the properties of the selected node as I expected. I'd
expect all the properties to become null references after
the node is removed, and they do...but why the error?

I figured at first that it was something stupid I didn't
know about OOP (I'm a died-in-the-wool C person) but I've
seen a couple of code examples that use basically
identical code to remove a node and just can't see what
I'm doing wrong.

TIA for someone's help with this! :)
Christy
 
Hello,

Christy Davids said:
I've got a context menu attached to a treeview with a menu
item for deleting a node in the treeview. The code for
the menu item click event is as follows:

Private Sub MenuItemDelete_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
MenuItemDelete.Click
Dim tvn As TreeNode = TreeView1.SelectedNode
tvn.Remove()
End Sub

This produces an "Object reference not set to an instance
of an object" error at the tvn.Remove(). Walking through
it in the debugger I can see that tvn is being set with
all the properties of the selected node as I expected. I'd
expect all the properties to become null references after
the node is removed, and they do...but why the error?

The problem is that the node is not selected when showing the context menu.

Quick and (very) Dirty:

\\\
Private Sub TreeView1_MouseUp( _
ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs _
) Handles TreeView1.MouseUp
If e.Button = MouseButtons.Right Then
Dim n As TreeNode = Me.TreeView1.GetNodeAt(e.X, e.Y)
If Not n Is Nothing Then
Me.TreeView1.SelectedNode = n
Me.MenuItem1.Text = n.Text
Else
Me.MenuItem1.Text = "(no item selected)"
End If
Me.ContextMenu1.Show(Me.TreeView1, New Point(e.X, e.Y))
End If
End Sub
///
 
Back
Top