Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to check how many rows in datareader[0] . and add top 5 numbers of data to listbox

What I have tried:

string query2 = "select Distinct OuterCode,OuterCode_Result,MasterCode,PalletCode from BatchDetails Where OuterCode_Result = 1 and " +
" MasterCode IS NULL and PalletCode IS NULL";
var dataReader = sqlDataReader1;

 while (dataReader.Read())
Posted
Updated 30-May-21 4:01am
Comments
Richard MacCutchan 30-May-21 7:41am    
What is the problem? Please show the complete code and explain what results you get.
Member 15212425 30-May-21 8:02am    
I want to check if datareader[0] count is greater than rowcount..
when fetching distinct values only ,dr[0] doesnt have rowcount number of data

int rowcount = Convert.ToInt32(Settings.Default["outercode"]);
string query2 = string.Format($" select Distinct top({ rowcount}) OuterCode,OuterCode_Result,MasterCode,PalletCode from BatchDetails Where OuterCode_Result = 1 and " +
" MasterCode IS NULL and PalletCode IS NULL");
using (SqlCommand sqlCommand = new SqlCommand(query2, sqlConn3))
{
sqlCommand.Parameters.AddWithValue("@OuterCode_Result", 1);
sqlCommand.Parameters.AddWithValue("@MasterCode", "NULL");
sqlCommand.Parameters.AddWithValue("@PalletCode", "NULL");
//sqlCommand.Parameters.Add(textBox2.Text,SqlDbType.Int);

SqlDataReader sqlDataReader1 = sqlCommand.ExecuteReader();

var dataReader = sqlDataReader1;

while (dataReader.Read())
{
if (datareader[0].count >= rowcount ){
listBox1.Items.Add(dataReader[0]);}
}

1 solution

DataReaders don't return a row count, because they don't return all the rows at once.
To find out how many rows you are going to get, you'd either have to read all the rows and count them then do your processing to read the rows again, or run a SELECT COUNT(*) FROM query before you issue the SELECT command to get the DataReader itself - and both solutions may return a different number of rows to those returned by your final DataReader because SQL Server is a multiuser system and the number of rows could easily change.

If you need to know how many rows, use a DataAdapter to fill a DataTable instead of a DataReader as that returns when all the rows are ready and supports a count.

If you only want up to five rows, then modify your query to retrieve only the ones you want:
SQL
SELECT TOP 5 DISTINCT ...
And add an ORDER BY clause or SQL can return rows in any order it deems fit.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900