在VB.NET中添加嵌套的Treeview节点?

时间:2011-07-12 09:44:21

标签: vb.net treeview

我正在尝试将一些项添加到TreeView控件中:

    TV1.Nodes.Add("key1", "Test1")  'Works
    TV1.Nodes("key1").Nodes.Add("key2", "Test2") 'Works (Nested)
    TV1.Nodes("key2").Nodes.Add("key3", "Test3") 'Error (NullReferenceException)

任何想法?谢谢:))

4 个答案:

答案 0 :(得分:1)

假设您想要的结构如下:

key1
-- key2
   -- key3

最后一行应该是: TV1.Nodes("key1").Nodes("key2").Nodes.Add("key3", "Test3")

或者

key1
-- key2
-- key3

使用TV1.Nodes("key1").Nodes.Add("key3", "Test3")

答案 1 :(得分:1)

我自己想通了:

    TV1.Nodes.Add("key1", "Test1")
    TV1.Nodes.Find("key1", True)(0).Nodes.Add("key2", "Test2")
    TV1.Nodes.Find("key2", True)(0).Nodes.Add("key3", "Test3")

答案 2 :(得分:0)

Public Class Test
  Dim CurrentNode As TreeNode

  Private Sub Search_and_Add(CurrentNode As TreeNode, NodesListArray() As String, Pointer As Integer)
    If Pointer >= NodesListArray.Length Then
      Exit Sub
    End If

    Dim BasisNodeExists As Integer = 0
    Dim BasisNodeGID As Integer = 0

    If Pointer = 0 Then
      For j As Integer = 0 To TreeView1.Nodes.Count - 1
        If TreeView1.Nodes(j).Text = NodesListArray(j) Then
          BasisNodeExists = 1
          BasisNodeGID = j
        End If
      Next

      If BasisNodeExists = 1 Then
        Search_and_Add(TreeView1.Nodes.Item(BasisNodeGID), NodesListArray, Pointer + 1)
      Else
        TreeView1.Nodes.Add(New TreeNode(NodesListArray(Pointer)))
        Search_and_Add(TreeView1.Nodes.Item(0), NodesListArray, Pointer + 1)
      End If
    Else
      Dim NewEntryRequired As Integer = 1
      For i As Integer = 0 To CurrentNode.Nodes.Count - 1
        If CurrentNode.Nodes.Item(i).Text = NodesListArray(Pointer) Then
          NewEntryRequired = 0
        End If
      Next
      If NewEntryRequired = 1 Then
        CurrentNode.Nodes.Add(New TreeNode(NodesListArray(Pointer)))
      End If
      For i As Integer = 0 To CurrentNode.Nodes.Count - 1
        If CurrentNode.Nodes.Item(i).Text = NodesListArray(Pointer) Then
          Search_and_Add(CurrentNode.Nodes.Item(i), NodesListArray, Pointer + 1)
        End If
      Next
    End If
  End Sub

  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Search_and_Add(New TreeNode(), New String() {"1", "2", "3"}, 0)
  End Sub
End Class

答案 3 :(得分:0)

这是一个简单的方法..

http://msdn.microsoft.com/en-us/library/system.windows.forms.treenode.parent.aspx

您可以使其更简单 - 只需使用IsNot检查并继续添加父节点是否存在。

BlueColorMan