Rellenar un TreeView con el schema de una DB Access

2128 vistas

Veamos cómo rellenar un TreeView con la estructura de una base de datos Access.



vbnet
  1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  2.     ' extraemos la estructura
  3.     Dim lstStructure As New SortedList
  4.     Dim MiConn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\User\NWIND.MDB;")
  5.     MiConn.Open()
  6.     Dim schemaTables As DataTable = MiConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
  7.     Dim MiEnumCol, MinEnumTable As IEnumerator
  8.     Dim schemaColTable As DataTable
  9.     Dim ListCol As ArrayList
  10.     MiEnumTable = schemaTables.Rows.GetEnumerator
  11.     While MiEnumTable.MoveNext
  12.         schemaColTable = MiConn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, New Object() {Nothing, Nothing, CType(MiEnumTable.Current, DataRow).Item("Table_Name"), Nothing})
  13.         ListCol = New ArrayList
  14.         MiEnumCol = schemaColTable.Rows.GetEnumerator
  15.         While MiEnumCol.MoveNext
  16.             ListCol.Add(CType(MiEnumCol.Current, DataRow).Item("column_name"))
  17.         End While
  18.         lstStructure.Add(CType(MiEnumTable.Current, DataRow).Item("Table_Name"), ListCol)
  19.     End While
  20.     MiConn.Close()
  21.  
  22.     ' rellenado del TreeView
  23.     Dim NodRoot, NodTable, NodTemp As TreeNode
  24.     NodRoot = Me.TreeView1.Nodes.Add("biblio.mdb")
  25.     NodRoot.ImageIndex = 0
  26.     Dim cmpt1, cmpt2 As Int32
  27.     Dim MiEnum As IEnumerator
  28.     For cmpt1 = 0 To lstStructure.Count - 1
  29.         NodTable = NodRoot.Nodes.Add(CType(lstStructure.GetKey(cmpt1), String))
  30.         MiEnum = CType(lstStructure.GetByIndex(cmpt1), ArrayList).GetEnumerator
  31.         While MiEnum.MoveNext
  32.             NodTemp = New TreeNode
  33.             With NodTemp
  34.                 .Text = CType(MiEnum.Current, String)
  35.                 .ImageIndex = 2
  36.             End With
  37.             NodTable.Nodes.Add(NodTemp)
  38.             NodTable.ImageIndex = 1
  39.         End While
  40.     Next
  41.     Me.TreeView1.ImageList = Me.ImageList1
  42.  
  43. End Sub