Note that this code is redundant from .NET 2.0, where you have the DataTable.Load method.
This example uses OleDb but the principle is directly transferable to all other Data namespaces.VB Code:
Public Function GetFilledTable(ByVal query As String, ByVal connection As OleDbConnection) As DataTable Dim command As New OleDbCommand(query, connection) connection.Open() Dim reader As OleDbDataReader = command.ExecuteReader(CommandBehavior.KeyInfo Or CommandBehavior.CloseConnection) Dim schema As DataTable = reader.GetSchemaTable() Dim columns(schema.Rows.Count - 1) As DataColumn Dim column As DataColumn 'Build the schema for the table that will contain the data. For i As Integer = 0 To columns.GetUpperBound(0) Step 1 column = New DataColumn column.AllowDBNull = CBool(schema.Rows(i)("AllowDBNull")) column.AutoIncrement = CBool(schema.Rows(i)("IsAutoIncrement")) column.ColumnName = CStr(schema.Rows(i)("ColumnName")) column.DataType = CType(schema.Rows(i)("DataType"), Type) If column.DataType Is GetType(String) Then column.MaxLength = CInt(schema.Rows(i)("ColumnSize")) End If column.ReadOnly = CBool(schema.Rows(i)("IsReadOnly")) column.Unique = CBool(schema.Rows(i)("IsUnique")) columns(i) = column Next i Dim data As New DataTable Dim row As DataRow data.Columns.AddRange(columns) 'Get the data itself. While reader.Read() row = data.NewRow() For i As Integer = 0 To columns.GetUpperBound(0) row(i) = reader(i) Next i data.Rows.Add(row) End While reader.Close() Return data End Function



Reply With Quote

