Programming for Everybody: Visual Basic.net: Populate Treeview in VB.Net with Access database(with Source Code)

Visual Basic.net: Populate Treeview in VB.Net with Access database(with Source Code)



 Imports System.Data

Imports System.Data.OleDb

Public Class Form3

    Private Function bind_data(ByVal strsql As String) As DataTable

        Dim dt As New DataTable

        Dim constr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Prog\Documents\sports.accdb"


        Using con As New OleDbConnection(constr)


            Using cmd As New OleDbCommand(strsql)


                Using sda As New OleDbDataAdapter()


                    cmd.CommandType = CommandType.Text

                    cmd.Connection = con

                    sda.SelectCommand = cmd


                    sda.Fill(dt)


                End Using


            End Using


            Return dt

        End Using

    End Function

    Private Sub ptreeview(ByVal dtparent As DataTable, ByVal parentid As Integer, ByVal tree1 As TreeNode)

        For Each row As DataRow In dtparent.Rows


            Dim child As New TreeNode() With { _

                .Text = row("name1").ToString(), _

                .Tag = row("id") _

            }

            If parentid = 0 Then


                TreeView1.Nodes.Add(child)


   Dim dtchild As DataTable = Me.bind_data("select id,name1 from names1 where id_sport=" & child.Tag)

                ptreeview(dtchild, Convert.ToInt32(child.Tag), child)

            Else

                tree1.Nodes.Add(child)

            End If

        Next

    End Sub


    Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim dt As DataTable = Me.bind_data("select id,name1 from sports1")

        Me.ptreeview(dt, 0, Nothing)

    End Sub

End Class

No comments:

Post a Comment