vb.net TreeView的selectedNode 返回NUll的问题
用vb.net 做了一个 treeView和contextmenustrip结合的程序,使用右键可以添加结点
部分代码如下:
Public Sub addPoint()
'添加断点
Dim treeNodeSection As New TreeNode
' Dim c As TreeView = frmMain.SectionContextMenuStrip.SourceControl
treeNodeSection = frmMain.tvwProgram.SelectedNode
MsgBox(treeNodeSection Is Nothing) '调试此对象是否为空
Dim strPointName As String = InputBox("请输入断点名称", "断点名称")
If strPointName.Trim <> "" Then
'MsgBox(strPointName)
'判断是否有同名的结点
If treeNodeSection.Nodes.Count > 0 Then
For Each node As TreeNode In treeNodeSection.Nodes
If strPointName.Trim = node.Text Then
MessageBox.Show("已经具有相同名称的断点", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Exit Sub
End If
Next
End If
treeNodeSection.Nodes.Add(strPointName)
End If
不明白的问题有三个地方:
1、Dim treeNodeSection As New TreeNode 这里我测试不用new也是可以的,所以请教vb里面什么时候需要new,最好是结合例子讲解,谢谢
2、调试程序时,发现一个很奇怪的问题,我在程序中有判断treeNodeSection 这个结点是否为null的代码(MsgBox(treeNodeSection Is Nothing) '调试此对象是否为空
). 在运行程序时,程序刚启动第一次调用此方法时,弹出 True,说明treeNodeSection是null, 但是以后调用时就都是弹出False,好生奇怪,请教解决方案。
3、For Each node As TreeNode In treeNodeSection.Nodes 这句代码有时候也会报错,怀疑是不是当treeNodeSection.Nodes为空时发生的,请教不知道还有没其他的可能?