Click here to Skip to main content
16,017,922 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I'm looking for a way to fill a treeview from mysql database, I found a code that fill treeview using by
Dictionary
but its work with two column and I have three column in my table it would be grate if someone help me to do it with three columns.

My Table :
Root_Name Child_Name Grandchild_Name
Root1 Child1 Grandchild1
Root1 Child1 Grandchild2
Root1 Child2
Root2 Child1
Root2 Child2 Grandchild1
Root3 Child1

What I have tried:

This code add many Root and thier Childs :

VB
Public Function fill_TreeViewProject() As DataTable
    DT_Project_tree_dt.Clear()
    MyQuery = ""
    Dim conString As String = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, userName, password, DatabaseName)
    Using con As New MySqlConnection(conString)
        MyQuery = "SELECT DISTINCT(Child), Root, Id FROM Project_tree;"

        Using cmd As New MySqlCommand(MyQuery, con)
            cmd.CommandType = CommandType.Text
            Using sda As New MySqlDataAdapter(cmd)
                Using DT_Project_tree_dt
                    sda.Fill(DT_Project_tree_dt)
                    Return DT_Project_tree_dt
                End Using
            End Using
        End Using
    End Using
End Function


VB
Public Sub Fill_Node_Tree()
        Tview_Nodes.Nodes.Clear()
        Dim dict As New Dictionary(Of String, List(Of String))()
        For Each row As Data.DataRow In fill_TreeViewProject.Rows
            Dim ParentRow As String = DirectCast(row.Item(1), String)
            Dim ChildRow As String = DirectCast(row.Item(0), String)

            If ParentRow Is Nothing OrElse ChildRow Is Nothing Then
                Continue For
            End If

            If dict.ContainsKey(ParentRow) Then
                'Add Child if parent already exist
                dict(ParentRow).Add(ChildRow)
            Else
                'Add parent if dosen't exist and attach the child
                dict.Add(ParentRow, New List(Of String)())
                dict(ParentRow).Add(ChildRow)
            End If
        Next

        Dim node As TreeNode

        For Each kvp In dict
            'Add Parent node
            node = New TreeNode(kvp.Key)
            Tview_Nodes.Nodes.Add(node)

            'Loop through list value and add to parent item as childs
            For Each chiled As String In kvp.Value
                node.Nodes.Add(chiled)
            Next


        Next
    End Sub
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900