Question: fill datatable with datareader

  • Thread starter Thread starter VB Programmer
  • Start date Start date
V

VB Programmer

I'm creating a generic sql "helper" function called "GetDataReader". This
is what I want it to do:

Inputs: DbConnectionString, SqlString

1. Connects to db using DbConnectionString
2. Gets data reader based on SqlString
3. Loop through it and fill a new datatable
4. Close all connections

How do I do #3? I do NOT have pre-defined column names, amount of columns,
etc...

Thanks!
 
--

W.G. Ryan, eMVP

Have an opinion on the effectiveness of Microsoft Embedded newsgroups?
Let Microsoft know!
https://www.windowsembeddedeval.com/community/newsgroups
VB Programmer said:
I'm creating a generic sql "helper" function called "GetDataReader". This
is what I want it to do:

Inputs: DbConnectionString, SqlString

1. Connects to db using DbConnectionString
2. Gets data reader based on SqlString
3. Loop through it and fill a new datatable
4. Close all connections

How do I do #3? I do NOT have pre-defined column names, amount of
columns,

In ADO.NET 2.0 you can load a DataTable from a Reader directly, in the
meantime you have to do it yourself. If I understand you correctly you can
do it a few ways. Assuming you don't know the structure beforehand, I think
you'll need to use GetSchemaTable to construct the table --- looping through
it to build the columns. Then run a while dr.Read() and inside that, add a
row each time setting each column value to the respective dr value/index.
Since a DataReader is used behind the scenes to fill a DataTable anyway,
it's probably a bit more work than it's worth - but that last part is just
purely an opinion.

This
http://www.dotnetjunkies.com/Article/9E031150-2995-4298-86A7-407D8349C8A8.dcik article should help you though.
 
Thanks William!

William Ryan eMVP said:
--

W.G. Ryan, eMVP

Have an opinion on the effectiveness of Microsoft Embedded newsgroups?
Let Microsoft know!
https://www.windowsembeddedeval.com/community/newsgroups

columns,

In ADO.NET 2.0 you can load a DataTable from a Reader directly, in the
meantime you have to do it yourself. If I understand you correctly you can
do it a few ways. Assuming you don't know the structure beforehand, I think
you'll need to use GetSchemaTable to construct the table --- looping through
it to build the columns. Then run a while dr.Read() and inside that, add a
row each time setting each column value to the respective dr value/index.
Since a DataReader is used behind the scenes to fill a DataTable anyway,
it's probably a bit more work than it's worth - but that last part is just
purely an opinion.

This
http://www.dotnetjunkies.com/Article/9E031150-2995-4298-86A7-407D8349C8A8.dcik
article should help you though.
 
Back
Top