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";
2
  • 4
    What is rep variable? Commented Oct 16, 2015 at 8: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 HasRows | Type: System.Boolean true if the SqlDataReader contains one or more rows; otherwise false. Commented Jan 19, 2022 at 23:30

4 Answers 4

37
 DataTable dt = new DataTable();
 dt.Load(reader);
 int numRows= dt.Rows.Count;
Sign up to request clarification or add additional context in comments.

1 Comment

Nice solution, but the .Load method consume the Reader (as obvius). For evryone that is looking for a method to count record without consuming the Reader (like create a counter in an existing portion of code) i'll save some time. It's simply not possible. You have to change the code and use DataTable.
33

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.

2 Comments

rep what type of variable is?
I think rep is a GridView
13

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

dataReader.Cast<object>().Count();

1 Comment

Are you saying the data reader can still be used at the end of this to iterate and load the actual data after having obtained a record count?
-10

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);
     }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.