开发者

Adding Nested Treeview Nodes in VB.NET?

I am trying to add some items to a TreeView Control:

    TV1.Nodes.Add("key1", "Test1")  'Works
    TV1.Nodes("key1").Nodes.Add("key2", "Test2") 'Works (Nested)
   开发者_开发知识库 TV1.Nodes("key2").Nodes.Add("key3", "Test3") 'Error (NullReferenceException)

any ideas? thanks :)


Assuming that the structure you want looks like:

key1
-- key2
   -- key3

the final line should be: TV1.Nodes("key1").Nodes("key2").Nodes.Add("key3", "Test3")

Or with

key1
-- key2
-- key3

Use TV1.Nodes("key1").Nodes.Add("key3", "Test3")


I figured it out myself:

    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")


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


Here is a simple way..

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

You can make it even simpler - Just use the IsNot check and go ahead to add if the parent node exists.

BlueColorMan

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜