atr*_*joe 18 c# sql sqldatareader
我试图通过迭代读取器获得返回的行数.但是当我运行这段代码时,我总是得到1?我搞砸了吗?
int count = 0;
if (reader.HasRows)
{
while (reader.Read())
{
count++;
rep.DataSource = reader;
rep.DataBind();
}
}
resultsnolabel.Text += " " + String.Format("{0}", count) + " Results";
Run Code Online (Sandbox Code Playgroud)
p.c*_*ell 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
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
if (reader.HasRows)
{
rep.DataSource = reader;
rep.DataBind();
}
int count = rep.Items.Count; //somehow count the num rows/items `rep` has.
Run Code Online (Sandbox Code Playgroud)
小智 10
DataTable dt = new DataTable();
dt.Load(reader);
int numRows= dt.Rows.Count;
Run Code Online (Sandbox Code Playgroud)
小智 8
这将为您提供行数,但会将数据读取器留在最后.
dataReader.Cast<object>().Count();
Run Code Online (Sandbox Code Playgroud)