Monday, April 23, 2012


VB.net Populate TreeView with DataSet using Parent-Child Relations

'Sub for calling a treeview update when needed
Private Sub updateTree()
    'Clear All Previous TreeView Nodes
    TreeView1.Nodes.Clear()
    'Loop Through the database examining the Parent child relationship and Add the nodes to the Tree
    Dim i As Integer = 0
    For Each table As DataTable In ds.Tables
        Dim node As New TreeNode(table.TableName)
        If table.ParentRelations.Count = 0 Then
            node.Text = table.TableName & " -Parent"
            node.Tag = table.TableName
            TreeView1.Nodes.Add(node)
        ElseIf table.ParentRelations.Count = 1 And table.ChildRelations.Count = 1 Then
            node.Tag = table.TableName
            node.Text = table.TableName & "-Child"
            TreeView1.Nodes(0).Nodes.Add(node)
        ElseIf table.ChildRelations.Count = 0 And table.ParentRelations.Count = 1 Then
            node.Tag = table.TableName
            node.Text = table.TableName & "-Grandchild"
            TreeView1.Nodes(0).Nodes(i).Nodes.Add(node)
            i += 1
        End If
    Next 

No comments:

Post a Comment