2011-03-31 21 views
13

Okuyucuyu yineleyerek döndürülen satır sayısını almaya çalışıyorum. Ama bu kodu çalıştırdığımda her zaman 1 alırım? Bu konuda bir şey mi berbat ettim?SQLDataReader Satır Sayımı

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

'rep' değişken nedir sayılmaz çeker? – bluish

cevap

22

SQLDataReaders yalnızca ileriye yöneliktir.

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

güzel ama okuyucuyu kapalı bırakacak –

6

Bu, satır sayısı alacak, ancak sonunda veri okuyucu bırakacaktır:

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 

yerine yapabilirsiniz: Sen aslında yapıyorsun.

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

Belki bu deneyebilirsiniz: lütfen unutmayın gerçi - Bu sütun sayısı, satır

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