SQLDataReader行计数

我试图通过迭代读取器获得返回的行数。 但是当我运行这段代码时,我总是得到1? 我搞砸了吗?

int count = 0; if (reader.HasRows) { while (reader.Read()) { count++; rep.DataSource = reader; rep.DataBind(); } } resultsnolabel.Text += " " + String.Format("{0}", count) + " Results"; 

SQLDataReaders是仅向前的。 你基本上是这样做的:

 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 

你可以这样做:

 if (reader.HasRows) { rep.DataSource = reader; rep.DataBind(); } int count = rep.Items.Count; //somehow count the num rows/items `rep` has. 
  DataTable dt = new DataTable(); dt.Load(reader); int numRows= dt.Rows.Count; 

这将为您提供行数,但会将数据读取器留在最后。

 dataReader.Cast().Count(); 

也许你可以试试这个:虽然请注意 – 这会拉动列数,而不是行数

  using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { int count = reader.VisibleFieldCount; Console.WriteLine(count); } }