2011-03-31 14 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

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 

आप इस के बजाय कर सकता है:

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

यह आपको पंक्ति संख्या मिल जाएगा, लेकिन अंत में डेटा पाठक छोड़ देंगे।

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

हो सकता है कि आप इस कोशिश कर सकते हैं: हालांकि, कृपया ध्यान दें - यह कॉलम गिनती, पंक्ति गिनती नहीं

using (SqlDataReader reader = command.ExecuteReader()) 
{ 
    while (reader.Read()) 
    { 
     int count = reader.VisibleFieldCount; 
     Console.WriteLine(count); 
    } 
} 
संबंधित मुद्दे