Miguel Angel
Miguel Angel

Reputation: 21

DataReader does not return data but the number of rows

I have this code

string query = "SELECT * FROM table;"

try
{
   using (SqlConnection connection = new SqlConnection(this.ConnectionString))
   {
      connection.Open();

      using (SqlCommand cmd = new SqlCommand(query, connection))
      {
         SqlDataReader reader = cmd.ExecuteReader();
      }

      connection.Close();
   }
}

In reader I receive the number of rows in the table, but no data. Where am I getting lost?

Upvotes: 0

Views: 272

Answers (2)

Gnah
Gnah

Reputation: 16

You need to read the reader

https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/retrieving-data-using-a-datareader#:~:text=To%20retrieve%20data%20using%20a,rows%20from%20a%20data%20source.

SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
    while (reader.Read())
    {
           // 
    }
}

Upvotes: 0

Sean
Sean

Reputation: 62472

Once you've called ExecuteReader you need to loop through it, reading each row:

while(reader.Read())
{
  // Process the row...
}

Also, it's good practice to put the reader into a using block:

using(SqlDataReader reader = cmd.ExecuteReader())
{
  while(reader.Read())
  {
    // Process the row
  }
}

Upvotes: 3

Related Questions