Donate

How Get Total Number Of Rows From SQLDataReader Object Using C#

Good Evening Gents!

In the office, we were using SQLDataReader class to read from SQL Server database in a straight-forward manner. The SQLDataReader has several properties that are commonly used such as HasRows and FieldCount. However in one of my task, I want to retrieve the total number of rows returned from the SQLDataReader object and there's no such property that support this. Doing some search led me to this link How to get number of rows using SqlDataReader in C#. The one that worked for me was the answer using select @@ROWCOUNT query. I modified his answer by writing my own method that will accept a List of SQLParameters given that the original query requires parameters.
private static void GetTotalRowCount(string query, string connectionString, ref int totalRows, List<SqlParameter> sqlParameters)
{
 try
 {
  using (var sqlCon = new SqlConnection(connectionString))
  {
   sqlCon.Open();
   var cmd = sqlCon.CreateCommand();
   cmd.CommandText = query;

   if (sqlParameters != null)
   {
    foreach (var param in sqlParameters)
    {
     cmd.Parameters.Add(new SqlParameter(param.ParameterName, param.Value));
    }
   }

   SqlDataReader reader = cmd.ExecuteReader();
   reader.Close();

   cmd.CommandText = "select @@ROWCOUNT";
   totalRows = Convert.ToInt32(cmd.ExecuteScalar());
  }
 }
 catch (Exception ex)
 {
  throw;
 }
}

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Pass GUID As Parameter To Action Using ASP.NET MVC ContribGrid