Alfie
Alfie

Reputation: 73

'System.InvalidOperationException: 'Invalid attempt to read when no data is present.' error in sql c#

I am trying to connect tot he database and extract the contents, but whenever I try, I get this error:

System.InvalidOperationException: Invalid attempt to read when no data is present.

I'm not sure why no data is being read from the table, it seems to work perfectly fine when I connect to the other table I have in the database.

This is the code I use:

static void testcon()
{
    SqlConnection con = new SqlConnection(Programe.connectionString);
    con.Open();

    SqlCommand cmd1 = new SqlCommand("SELECT * FROM Auth WHERE Username = @username", con);
    cmd1.Parameters.AddWithValue("username", "test");

    SqlDataReader reader = cmd1.ExecuteReader();

    Console.WriteLine(reader[0]);

    con.Close();
}

The exception was thrown on this line of code:

Console.WriteLine(reader[0]);

This is the server explorer:

enter image description here

I have tried trying different key words in the SQL commands, different keywords in the method but I keep getting the same error.

I have tried

if (reader.read())
{
    //code here
}

but that wouldn't solve my issue as the data not being present would still occur

Upvotes: 1

Views: 715

Answers (2)

ShubhamWagh
ShubhamWagh

Reputation: 645

try this.

You can print column name as per your need.

using (SqlDataReader reader = cmd1.ExecuteReader())
{
      while (reader.Read()) //The loop will run for all the rows in the result.
      {
          //loop on all the columns
          for (int i = 0; i < reader.FieldCount; i++)
          {
              Console.WriteLine(reader.GetValue(i));
          }
          Console.WriteLine();
       }
 }

Upvotes: 2

Indept Studios
Indept Studios

Reputation: 86

Try

while(reader.read())
{
// code here
}

Upvotes: 1

Related Questions