Fill a datatable from a datareader?

T

Tom

Is there any direct way to fill a datatable from a datareader? Or do
we -have- to use a dataadapter?

Tom
 
C

Cor

Hi Tom,

There is no problem at all, but why would you do it.
This I did copy from a complete sample I did give some threads bellow.

But I would not do it that way, it was to show how the datatable did look I
thought.

The dataadapter does this for you in 2 lines of code.
\\\
Dim ds1 As DataSet = New DataSet
Dim dt1 As New DataTable("tbl1")
Dim dca As New DataColumn("a", Type.GetType("System.Int32"))
Dim dcb As New DataColumn("b", Type.GetType("System.String"))
dt1.Columns.Add(dca)
dt1.Columns.Add(dcb)
ds1.Tables.Add(dt1)
cmd1.CommandText = "Select a, b from tbl1"
Dim rdr As OleDb.OleDbDataReader
rdr = cmd1.ExecuteReader()
While rdr.Read()
Dim dr As DataRow
dr = ds1.Tables(0).NewRow
dr("a") = rdr.GetInt32(0)
dr("b") = rdr.GetString(1)
ds1.Tables(0).Rows.Add(dr)
End While
rdr.Close()
///
 
W

William Ryan [eMVP]

Tom:

Like Cor mentions, you can do it using an iterative approach, but whether or
not you want to is another story. Behind the scenes, DataAdapter.Fill uses
a DataReader to populate the datatable and in my experience, the performance
differences are virtually unnoticeable. However, you are adding some more
complexity here, namely that you are going ot have to be responsible for
opening and closing the connection and that you don't overrun any indexes
etc...and it's just a lot more code. I can't say it's the case in every
situation, but it's fair to say that most of the time,if you need the
functionality of a DataTable over a reader, it's probably better to just use
DataAdapter.fill

HTH,

BIll
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top