26

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";
Abbas
  • 6,720
  • 4
  • 35
  • 49
atrljoe
  • 8,031
  • 11
  • 67
  • 110
  • 4
    What is `rep` variable? – bluish Oct 16 '15 at 08:18
  • Please note `HasRows` is useful for those of us who just want to distinguish between 1 or more rows (`HasRows==true`) and 0 zero rows (`HasRows == false`), [more here](https://stackoverflow.com/a/12609979/1175496) `HasRows | Type: System.Boolean true if the SqlDataReader contains one or more rows; otherwise false.` – Nate Anderson Jan 19 '22 at 23:30

4 Answers4

35
 DataTable dt = new DataTable();
 dt.Load(reader);
 int numRows= dt.Rows.Count;
Roozi
  • 683
  • 6
  • 12
32

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.
p.campbell
  • 98,673
  • 67
  • 256
  • 322
13

This will get you the row count, but will leave the data reader at the end.

dataReader.Cast<object>().Count();
Gary
  • 161
  • 1
  • 4
-9

Maybe you can try this: though please note - This pulls the column count, not the row count

 using (SqlDataReader reader = command.ExecuteReader())
 {
     while (reader.Read())
     {
         int count = reader.VisibleFieldCount;
         Console.WriteLine(count);
     }
 }
Stuart.Sklinar
  • 3,683
  • 4
  • 35
  • 89
pjiaquan
  • 87
  • 1
  • 2