(VB.Net, WinForm) I am not having much success in populating a
TreeView
three levels deep. I've tried different code from various sources but those I tried got me nowhere.
I am retrieving my
Nodes
from a database. The table looks like this:
catID | catName | catParent | catImage
For all Root Nodes the "catParent" will contain no data. For all other Nodes the catParent will contain the Parent Node it belongs to. Do not confuse Parent node with Root node.
I first tried the following code (found almost everywhere, even here on CodeProject). I thought to use the
.Find
option as it meant that I just had to search for the Name of my Parent Node since Indexes aren't unique.
Private Sub PopulateDocumentCategories()
tvDocuments.Nodes.Clear()
clReadFromDB.GetDocCategories()
For i = 0 To clReadFromDB.catData.Rows.Count - 1
If clReadFromDB.catData.Rows(i).Item(2) = "" Then
tvDocuments.Nodes.Add(New System.Windows.Forms.TreeNode(clReadFromDB.catData.Rows(i).Item(1), _
clReadFromDB.catData.Rows(i).Item(3), _
clReadFromDB.catData.Rows(i).Item(3)))
Else
Try
Dim tn As TreeNode() = tvDocuments.Nodes(0).Nodes.Find(clReadFromDB.catData.Rows(i).Item(2).ToString, True)
For j As Integer = 0 To tn.Length - 1
tvDocuments.SelectedNode = tn(j)
tvDocuments.Nodes.Add(New System.Windows.Forms.TreeNode(clReadFromDB.catData.Rows(i).Item(1), _
clReadFromDB.catData.Rows(i).Item(3), _
clReadFromDB.catData.Rows(i).Item(3)))
Next
Catch
End Try
Next i
tvDocuments.ExpandAll()
End Sub
This only adds the Root Nodes to the TreeView control and ignores all other nodes.
Went back to the drawing board and came up with the following code which actually populates the TreeView with the Root Nodes (Tier 1) and first level Child Nodes (Tier 2 Parent Nodes). However it does not add the last level of nodes (Tier 3).
Private Sub PopulateDocumentCategories()
tvDocuments.Nodes.Clear()
clReadFromDB.GetDocCategories()
For i = 0 To clReadFromDB.catData.Rows.Count - 1
If clReadFromDB.catData.Rows(i).Item(2) = "" Then
tvDocuments.Nodes.Add(New System.Windows.Forms.TreeNode(clReadFromDB.catData.Rows(i).Item(1), _
clReadFromDB.catData.Rows(i).Item(3), _
clReadFromDB.catData.Rows(i).Item(3)))
Else
For Each node As TreeNode In tvDocuments.Nodes
If node.Text = clReadFromDB.catData.Rows(i).Item(2) Then
tvDocuments.SelectedNode = node
tvDocuments.SelectedNode.Nodes.Add(New System.Windows.Forms.TreeNode(clReadFromDB.catData.Rows(i).Item(1), _
clReadFromDB.catData.Rows(i).Item(3), _
clReadFromDB.catData.Rows(i).Item(3)))
End If
Next node
End If
Next i
tvDocuments.ExpandAll()
End Sub
Is there something that I am doing wrong or not considering while populating the TreeView programmatically ?