2011-03-31 20 views
13

Estoy intentando obtener el número de filas que se devolvieron al iterar el lector. Pero siempre obtengo 1 cuando ejecuto este código? ¿Metí la pata en algo así?Recuento de fila SQLDataReader

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

¿Cuál es la variable 'rep'? – bluish

Respuesta

22

SQLDataReader son solo reenvíos. Básicamente 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 

que podría 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. 
7
DataTable dt = new DataTable(); 
dt.Load(reader); 
int numRows= dt.Rows.Count; 
+0

es agradable, pero dejará el lector cerrado –

6

Esto le dará el número de filas, pero dejará el lector de datos al final.

dataReader.Cast<object>().Count(); 
0

Tal vez usted puede intentar esto: aunque tenga en cuenta - Esta tira del número de columnas, no cuenta la fila

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