-1

How to get the length of a datareader, something like:

sqlDataReader dr = command.ExecuteReader();
dr.Read();

int L= dr.Length;// this doesn't work.

?

Aan
  • 12,247
  • 36
  • 89
  • 150

3 Answers3

6

You can keep track of how many items you've already read from the DataReader simply by using a counter. However, I don't believe there's any general way of finding out how many rows there will be without just reading them:

int count = 0;
while (dr.Read())
{
    // Use the row data, presumably
    count++;
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

I don't think the Datareader provides a Count property on itself. You would need whether to loop the datareader and increment a variable OR perform first a select count(*) with the same conditions you use in your command execution.

Laurent S.
  • 6,816
  • 2
  • 28
  • 40
0

There is no direct method (At least I don't know) to count the rows or columns. Use a custom counter in your while loop.

  • Find out by reading all rows as a custom operation. Like;

while(dr.Read())
{
     // Do your operations..
     counter++;
}
  • Run a query like Select Count(*) before your operation.
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364