views:

111

answers:

2

Hey,

After connecting to a database using DataReader, how can I count the number of rows ?

Thanks.

+1  A: 

Data readers are forward only so they don't have the count when first filled. You can do several things to address this:

  1. Run a separate command to get the count OR using NextResult to help instead of a totally separate command).
  2. Loop through the results and count the records
  3. Use a DataSet

Here's an example of #1:

Without NextResult: http://www.devx.com/vb2themax/Tip/18807

With NextResult (Doesn't return record count but gives you idea of how to use NextResult): http://bytes.com/topic/asp-net/answers/295793-datareader-nextresults-question

Here's an example of #2: http://support.microsoft.com/kb/308050

klabranche
+1  A: 

Only by repeatedly calling Read().

A DataReader is a forward-only view of a resultset and cannot get a count.

SLaks