2011-03-31 2 views
13

독자를 반복하여 반환 된 행 수를 얻으려고합니다. 하지만이 코드를 실행할 때 항상 1을 얻습니다. 이 일에 뭔가 망쳐 놨니?SQLDataReader 행 수

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

'rep' 변수는 무엇입니까 포함되지를 가져옵니다? – bluish

답변

22

SQLDataReader는 전달 전용입니다.

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

멋지지만 독자를 닫을 수 있습니다. –

6

이 당신에게 행 수를 얻을 것이다,하지만 마지막에 데이터 판독기를 떠나 :

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 

당신은 대신이 작업을 수행 할 수 있습니다 : 당신은 기본적으로이 일을하고 있습니다.

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

어쩌면 당신이 시도 할 수 있습니다 :주의하시기 바랍니다하지만 -이 열 수, 행이

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