[OleDB] DB-Daten in einem Treeview anzeigen

Public Sub RefreshTree()
    Dim DB_OleDBCommand As New System.Data.OleDb.OleDbCommand
    Dim DB_OleDBReader As System.Data.OleDb.OleDbDataReader

    ' wenn Datenverbindung offen Daten von DB holen
    If frmMain.DB_OleDBConnection.State = System.Data.ConnectionState.Open Then
        With DB_OleDBCommand
            .CommandText = "SELECT ID, Name FROM Users ORDER BY Name"
            .Connection = frmMain.DB_OleDBConnection
            DB_OleDBReader = .ExecuteReader()
        End With

        Dim tnRootNode As TreeNode
        Dim tnObjectNode As TreeNode

        ' TreeView leeren
        tvObjects.Nodes.Clear()

        ' Rootnode anlegen
        tnRootNode = tvObjects.Nodes.Add("Users")

        ' Daten aus DB in TreeView füllen
        Do While (DB_OleDBReader.Read())
            tnObjectNode = tnRootNode.Nodes.Add(DB_OleDBReader.Item("Name").ToString)
            ' ID in das Node-Tag schreiben, für spätere Referenzierung des Datensatzes
            tnObjectNode.Tag = DB_OleDBReader.Item("ID")
        Loop

        ' Verbindung schließen
        DB_OleDBReader.Close()

        ' Obj. löschen
        DB_OleDBCommand.Dispose()
        DB_OleDBCommand = Nothing

        ' Rootnode aufklappen
        tnRootNode.Expand()
    End If
End Sub

Schreibe einen Kommentar