我试图通过迭代读取器来获取返回的行数。但是当我运行这段代码时,我总是得到1?我搞砸了吗?
int count = 0;
if (reader.HasRows)
{
while (reader.Read())
{
count++;
rep.DataSource = reader;
rep.DataBind();
}
}
resultsnolabel.Text += " " + String.Format("{0}", count) + " Results";
答案 0 :(得分:25)
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.
答案 1 :(得分:9)
DataTable dt = new DataTable();
dt.Load(reader);
int numRows= dt.Rows.Count;
答案 2 :(得分:7)
这将为您提供行数,但会将数据阅读器留在最后。
dataReader.Cast<object>().Count();
答案 3 :(得分:-3)
也许你可以试试这个:虽然请注意 - 这会拉动列数,而不是行数
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int count = reader.VisibleFieldCount;
Console.WriteLine(count);
}
}