Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLDataReader Row Count

Tags:

I am trying to get the number of rows that were returned by iterating the reader. But I always get 1 when I run this code? Did I screw up something in this?

int count = 0; if (reader.HasRows) {     while (reader.Read())     {         count++;         rep.DataSource = reader;         rep.DataBind();     } } resultsnolabel.Text += " " + String.Format("{0}", count) + " Results"; 
like image 374
atrljoe Avatar asked Mar 31 '11 16:03

atrljoe


People also ask

What is SqlDataReader in Ado net?

ADO.NET SqlDataReader Class. This class is used to read data from SQL Server database. It reads data in forward-only stream of rows from a SQL Server database. it is sealed class so that cannot be inherited.

Is there anything faster than SqlDataReader in net?

Caching namespace. If you're doing purely data operations (as your question suggests), you could rewrite your code which is using the data to be T-SQL and run natively on SQL. This has the potential to be much faster, as you will be working with the data directly and not shifting it about.

How do I get data from ExecuteReader?

To retrieve data using a DataReader, create an instance of the Command object, and then create a DataReader by calling Command. ExecuteReader to retrieve rows from a data source.


2 Answers

SQLDataReaders are forward-only. You're essentially doing this:

count++;  // initially 1 .DataBind(); //consuming all the records  //next iteration on .Read() //we've now come to end of resultset, thanks to the DataBind() //count is still 1  

You could do this instead:

if (reader.HasRows) {     rep.DataSource = reader;     rep.DataBind(); } int count = rep.Items.Count; //somehow count the num rows/items `rep` has. 
like image 137
p.campbell Avatar answered Oct 24 '22 07:10

p.campbell


 DataTable dt = new DataTable();  dt.Load(reader);  int numRows= dt.Rows.Count; 
like image 21
Roozi Avatar answered Oct 24 '22 08:10

Roozi