Estoy tratando de obtener el número de filas que se devolvieron mediante la iteración del lector. Pero siempre obtengo 1 cuando ejecuto este código? ¿He jodido algo en esto?
int count = 0; if (reader.HasRows) { while (reader.Read()) { count++; rep.DataSource = reader; rep.DataBind(); } } resultsnolabel.Text += " " + String.Format("{0}", count) + " Results";
Los SQLDataReaders son solo hacia adelante. Esencialmente estás haciendo esto:
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
Podrías hacer esto en su lugar:
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;
Esto te dará el conteo de filas, pero dejará el lector de datos al final.
dataReader.Cast
Tal vez pueda intentar esto: aunque tenga en cuenta: esto extrae el recuento de columnas, no el recuento de filas
using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { int count = reader.VisibleFieldCount; Console.WriteLine(count); } }