[c#] SQLDataReader Row Count

I am trying to get the number of rows that were returned by iterating the reader. But I always get 1 when I run this code? Did I screw up something in this?

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

This question is related to c# sql sqldatareader

The answer is


This will get you the row count, but will leave the data reader at the end.

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

 DataTable dt = new DataTable();
 dt.Load(reader);
 int numRows= dt.Rows.Count;

Maybe you can try this: though please note - This pulls the column count, not the row count

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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sqldatareader

How do I get values from a SQL database into textboxes using C#? SQLDataReader Row Count Read data from SqlDataReader SQL Data Reader - handling Null column values How to get number of rows using SqlDataReader in C# Invalid attempt to read when no data is present how to check if a datareader is null or empty Can you get the column names from a SqlDataReader? Check for column name in a SqlDataReader object