Search code examples
c#recorddatareader

How to get the number of records in a Data Reader?


I'm trying to display the number of records in the data reader. Here's what I tried.

if (mybtnreader1.HasRows)
{
   using (DataTable dt = new DataTable())
   {
       dt.Load(mybtnreader1);
       int rc = dt.Rows.Count;
       MessageBox.Show("Have "+rc+"records");
   }
} 

Though it has records it is always displaying 0. How should it be corrected or is there any other way to get the number of records in a data reader?

I'm using this code to display the data.

while(mybtnreader1.Read())
{
    MessageBox.Show(mybtnreader1.GetValue(0) + "  "+mybtnreader1.GetValue(1)+" ");
}

It is showing the data but when it comes to the number of records it is displaying 0.


Solution

  • After looping through the results of your query you can use RecordsAffected:

    mybtnreader1 = command.ExecuteReader();
    
     while(mybtnreader1.Read())
            {
    
              ///do your stuff
            }
    
    mybtnreader1 .Close();
    MessageBox.Show(mybtnreader1 .RecordsAffected.ToString());