Public Class Categories
Dim dt As DataTable
Dim dr As DataRow
Dim tn As TreeNode
Private Sub Categories_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dt = Main.dtCats
'if the category list is still being downloaded show the please wait message.
lblMessage.Visible = True
trvCats.ImageList = ImageList1
End Sub
Private Sub Categories_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
If dt.Rows.Count > 1 Then
loadLIst()
End If
End Sub
'///
'This method loads the initial top level parents and any associated child items
'///
Public Sub loadList()
'Hide the please wait message
lblMessage.Visible = False
For Each dr In dt.Rows
If dr("level") = "1" Then
tn = New TreeNode
tn.Text = dr("name")
tn.Name = dr("CatID")
'check if the node is a leaf category, if so set the images required
If dr("leaf") Then
tn.ImageIndex = 2
tn.SelectedImageIndex = 2
End If
trvCats.Nodes.Add(tn)
AddChildNodes(tn)
End If
Next
End Sub
'///
'This method add the child nodes to the parent node
'///
Private Sub AddChildNodes(ByVal tn As TreeNode)
If tn.Nodes.Count = 0 Then
Dim childNode As TreeNode
For Each dr As DataRow In dt.Rows
'find the rows that have the same parent ID but not the same name
'as this will add a duplicate of the parent category to the list
If dr("ParentID") = tn.Name AndAlso dr("name") <> tn.Text Then
childNode = New TreeNode
childNode.Text = dr("name")
childNode.Name = dr("CatID")
'if the category is a leaf then add the appropriate image
If dr("leaf") Then
childNode.ImageIndex = 2
childNode.SelectedImageIndex = 2
End If
'add the node to the collection
tn.Nodes.Add(childNode)
End If
Next
End If
End Sub
Private Sub trvCats_AfterCollapse(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles trvCats.AfterCollapse
'node has been collapsed so reset the image displayed
e.Node.ImageIndex = 0
End Sub
Private Sub trvCats_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles trvCats.AfterSelect
'get the id of the selected node
tn = e.Node
AddChildNodes(tn)
For Each node As TreeNode In tn.Nodes
AddChildNodes(node)
Next
End Sub
Private Sub trvCats_BeforeExpand(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles trvCats.BeforeExpand
'get the id of the selected node
tn = e.Node
'node is being expanded so change the image displayed
tn.ImageIndex = 1
AddChildNodes(tn)
For Each node As TreeNode In tn.Nodes
AddChildNodes(node)
Next
End Sub
End Class