Sunday, August 19, 2007

Using GetSchemaTable to get Info about Columns in VB.NET

Here is a simple example in VB.NET that uses GetSchemaTable to retrieve information about the columns returned from a SQL Select statement. If you say "Select * from table", this method is useful for learning what information you will have returned. For a C# example and more information on the topic, look here.

Dim myConn As New OleDbConnection(ConnectionString)

Dim sql As String = "Select * from Table_ABC"

Dim myCommand As New OleDbCommand(sql, myConn)

myConn.Open()

Dim objDR As OleDbDataReader

objDR = myCommand.ExecuteReader(CommandBehavior.CloseConnection)


' Retrieve column schema into a DataTable.
Dim schemaTable As DataTable
schemaTable = objDR.GetSchemaTable()

' For each field in the table...
For Each myField As DataRow In schemaTable.Rows

' For each property of the field...
For Each myProperty As DataColumn In schemaTable.Columns

'Display the field name and value.
Debug.WriteLine(myProperty.ColumnName + _
" = " + myField(myProperty).ToString())

Next

Debug.WriteLine("")

Next

No comments: