No RecordCount property exists to indicate how many records are being fetched when you use the OleDbDataReader or SqlDataReader class in Visual C#

For a Microsoft Visual Basic .NET version of this article, see 308050 .

This article refers to the following Microsoft .NET Framework Class Library namespaces:

  • System.Data
  • System.Data.SqlClient


When you use the OleDbDataReader or SqlDataReader class, no RecordCount property exists to indicate how many records are being fetched.


The DataReader object or the back-end data source does not typically know how many records are being fetched until the last record is sent to the client.

Even an ActiveX Data Objects (ADO) Recordset returns -1 for the RecordCount property when it uses a forward-only cursor to retrieve data. DataReader exhibits similar behavior because it uses a forward-only cursor to retrieve rows and columns.


To work around this problem, use one of the following methods:
  • Count the records as you go through the reader.
  • Run a SELECT COUNT(*) query first. Note that this query may be out of date by the time you finish reading the data.


This behavior is by design.

More Information

Steps to reproduce the behavior

  1. Start Microsoft Visual Studio .NET.
  2. Create a new Windows Application in Visual C# .NET. Form1 is created by default.
  3. Make sure that your project contains a reference to the System.Data namespace, and add a reference to this namespace if it does not.
  4. Add a Command button to Form1, and change its Name property and its Text property to btnTest.
  5. Use the using statement on the System and System.Data namespaces so that you are not required to qualify declarations in those namespaces later in your code.
    using System;
    using System.Data;
    using System.Data.SqlClient;
  6. Return to Form view, and double-click btnTest to add the click event handler. Add the following code to the handler:
        String myConnString = 
    "User ID=sa;password=sa;Initial Catalog=pubs;Data Source=mySQLServer";

    String mySelectQuery = "SELECT * FROM Authors";
    SqlConnection myConnection = new SqlConnection(myConnString);
    SqlCommand myCommand = new SqlCommand(mySelectQuery, myConnection);

    SqlDataReader myReader ;
    myReader = myCommand.ExecuteReader();
    int RecordCount = 0;

    while (myReader.Read())
    if (RecordCount == 0)
    MessageBox.Show("No data returned");
    MessageBox.Show("Number of Records returned: " + RecordCount);
    catch (Exception ex)
  7. Modify the connection string (myConnString) as appropriate for your environment.
  8. Save your project.
  9. On the Debug menu, click Start to run your project.
  10. Click on the button. Notice that you can see the record count.


For more information, click the following article number to view the article in the Microsoft Knowledge Base:

194973 ADO: Recordcount may return -1


Article ID: 308352 - Last Review: Aug 4, 2008 - Revision: 1