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.
- 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.
Steps to reproduce the behavior
- Start Microsoft Visual Studio .NET.
- Create a new Windows Application in Visual C# .NET. Form1 is created by default.
- Make sure that your project contains a reference to the System.Data namespace, and add a reference to this namespace if it does not.
- Add a Command button to Form1, and change its Name property and its Text property to btnTest.
- 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.
- 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;
if (RecordCount == 0)
MessageBox.Show("No data returned");
MessageBox.Show("Number of Records returned: " + RecordCount);
catch (Exception ex)
- Modify the connection string (myConnString) as appropriate for your environment.
- Save your project.
- On the Debug menu, click Start to run your project.
- Click on the button. Notice that you can see the record count.