title: Adding Child Nodes to Childe Nodes on TreeView in VB
body: <p>I have a DataTable that can have 1 to 14 columns, i think. I wish to create a TreeView so that the data presented can be better sorted through. The problem is that when i loop through the datatable, it does not correctly format the tree. In fact, it only gets the root node and a child node, but it adds the child node multiple times. Now i could brute force it to work, but that is inefficient. So if anyone can help me out.</p>
  
  <p><img src="https://i.stack.imgur.com/XbVCA.png" alt="A data table that is used">
  <img src="https://i.stack.imgur.com/1SiWe.png" alt="What it should look like in the tree"></p>
  
  <p>Code: (Ignore the <code>.Count - 5</code>)</p>
  
  <pre><code>Public Sub loadTreeView()
  
      compClass.treeView.Nodes.Clear()
  
      Dim row As DataRow
      Dim parentNode As TreeNode
      Dim childNode As TreeNode
  
      Dim count As Integer = compClass.dataTable.Columns.Count - 5
  
      Dim test(count) As TreeNode
  
      For Each row In compClass.dataTable.Rows
  
          For i As Integer = 0 To count
  
              If i = 0 Then
                  test(i) = searchNode(row.Item(i).ToString())
                  If test(i) IsNot Nothing Then
                  Else
                      test(i) = New TreeNode(row.Item(i).ToString())
                      compClass.treeView.Nodes.Add(test(i))
                  End If
                  'parentNode = searchNode(row.Item(0).ToString())
                  'If parentNode IsNot Nothing Then
                  'Else
                  '    parentNode = New TreeNode(row.Item(0).ToString())
                  '    compClass.treeView.Nodes.Add(parentNode)
                  'End If
              Else
                  childNode = searchNode(row.Item(i - 1).ToString())
                  If childNode IsNot Nothing Then
                      test(i) = New TreeNode(row.Item(i).ToString())
                      test(i - 1).Nodes.Add(test(i))
                  End If
                  'parentNode = searchNode(row.Item(i - 1).ToString())
                  'If parentNode IsNot Nothing Then
                  '    childNode = New TreeNode(row.Item(i).ToString())
                  '    parentNode.Nodes.Add(childNode)
                  'End If
              End If
          Next
      Next
  End Sub
  
  Private Function searchNode(ByVal nodeText As String)
      For Each node As TreeNode In compClass.treeView.Nodes
          If node.Text = nodeText Then
              Return node
          End If
      Next
  
  End Function
  </code></pre>