SQLDataReader Row Count

前端 未结 4 510
情歌与酒
情歌与酒 2021-01-03 22:42

I am trying to get the number of rows that were returned by iterating the reader. But I always get 1 when I run this code? Did I screw up something in this?

         


        
相关标签:
4条回答
  • 2021-01-03 23:15
     DataTable dt = new DataTable();
     dt.Load(reader);
     int numRows= dt.Rows.Count;
    
    0 讨论(0)
  • 2021-01-03 23:17

    This will get you the row count, but will leave the data reader at the end.

    dataReader.Cast<object>().Count();
    
    0 讨论(0)
  • 2021-01-03 23:20

    SQLDataReaders are forward-only. You're essentially doing this:

    count++;  // initially 1
    .DataBind(); //consuming all the records
    
    //next iteration on
    .Read()
    //we've now come to end of resultset, thanks to the DataBind()
    //count is still 1 
    

    You could do this instead:

    if (reader.HasRows)
    {
        rep.DataSource = reader;
        rep.DataBind();
    }
    int count = rep.Items.Count; //somehow count the num rows/items `rep` has.
    
    0 讨论(0)
  • 2021-01-03 23:22

    Maybe you can try this: though please note - This pulls the column count, not the row count

     using (SqlDataReader reader = command.ExecuteReader())
     {
         while (reader.Read())
         {
             int count = reader.VisibleFieldCount;
             Console.WriteLine(count);
         }
     }
    
    0 讨论(0)
提交回复
热议问题