Friday, June 25, 2010

Convert SQLDataReader to DataTable

In ADO.Net SQLDataReader is a way of reading forward-only streams of sql server database.
SqlDataReader cannot be inherited. Only one SqlDataReader can open on associated SQL Connection.

This function is handy in the case of you want to store result of the reader to table and want to open further SqlDataReader on same SQL Connection.

This function receives SqlDataReader as Input and return DataTable as return

Public Function ReaderToTable(ByVal LReader As SqlDataReader) As Data.DataTable
Dim LTable As New Data.DataTable
Dim I As Integer
'Create table structure and get data type from each column
For I = 0 To LReader.FieldCount - 1
LTable.Columns.Add(LReader.GetName(I).ToString(), LReader.GetFieldType(I))
Next

'now start writing the rows
Do While LReader.Read()
Dim DRow As DataRow
DRow = LTable.Rows.Add()
For I = 0 To LReader.FieldCount - 1
DRow.Item(LTable.Columns(I).ColumnName) = LReader.Item(I)
Next
Loop

'give a name to table
LTable.TableName = "Reader"
Return LTable
End Function


No comments:

Post a Comment