0

I am getting this error on my login form. I am unsure on fixing it because I do not know what's wrong.

InvalidOperationException: no current row

When I start the app, it crashes.

enter image description here

     private void buttonLogin_Click(object sender, EventArgs e)
    {
         SQLiteConnection conn = new SQLiteConnection("data source = zivali_v2.sqlite");
         conn.Open();
         SQLiteCommand com = new SQLiteCommand(conn);

         com.CommandText = "SELECT * FROM login;";

         SQLiteDataReader reader = com.ExecuteReader();

             string username = reader["username"].ToString();
             string password = reader["password"].ToString();

         bool loginValid = false;
         while (reader.Read())
         {
             if (username == textBoxUserName.Text && password == textBoxPassword.Text)
             {
                 loginValid = true;
                 break;

             }
         }

         if (loginValid)
         {
             MessageBox.Show("OK");
         }
         else
         {
             MessageBox.Show("Wrong username or password");
         }
         conn.Close();

    }
krneki
  • 25
  • 2
  • 11

1 Answers1

0

A reader object represents a query's result, which is shaped like a table, i.e., it has columns and rows.

An expression like reader["username"] reads the value in the specified column and in the current row. But before the first Read() call, there is no current row. This is what the error message is telling you.

You must not move the reader["username"] call out of the loop; you have to make a call in each loop iteration to get a new value from each row:

while (reader.Read()) {
    username = reader["username"] ...
}

(And it would be a better idea to let the database use the comparisons, and to use parameters.)

CL.
  • 173,858
  • 17
  • 217
  • 259