我试图通过迭代读取器来获取返回的行数。但是运行此代码时,我总是得到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.