James
James

Reputation: 170

Issue while loading data from data reader to data table

When I am loading the data from data reader to data table than it skips the very first row. For example,if I have 12 rows in data reader than in data table only 11 rows are coming.

dataReader dr=new DataReader();
DataTable dt=new DataTable();
if(dr.read)    
dt.load(dr); 

Please help Thanx in advance!!!

Upvotes: 0

Views: 915

Answers (2)

Paddy
Paddy

Reputation: 33857

Looking at the documentation, the Load method is passed a DataReader without a check for:

if (dr.Read())

So I would say that if you removed this line, then you will get all your results. Read() will advance the reader by one record.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460138

DataReader.Read advances the reader to the next row.

You don't need this check, otherwise use HasRows instead.

dt.load(dr); 

Note that you also could use a DataAdapter to load the DataTable:

DataTable dt = new DataTable();
using(var con = new SqlConnection("ConnectionString"))
using(var da = new SqlDataAdapter("SELECT * FROM T", con))
{
    da.Fill(dt);
}

Upvotes: 2

Related Questions