S.R
S.R

Reputation: 27

While loop is not functioning correctly

I have a login program that have a user name texbox and password textbox. The program should get the user's name and password from the user and matching it with the name and password that is available in the access database file. The file is in bin/debug folder. The problem is the while loop is not working and I am getting only "Incorrect username and password message" from the loop. Can anyone help me please? Here is my code:

private void loginButton_Click(object sender, EventArgs e)
{
     try
     {     
         connection.Open();
         OleDbCommand command = new OleDbCommand();
         command.Connection = connection;
         command.CommandText = "select * from login where UserName= '" + userTextBox.Text + "'and Password= '" + passwordTextBOx.Text + "'";
         OleDbDataReader reader = command.ExecuteReader();
         int count = 0;
         while (reader.Read())
         {
             count = count + 1;
         }
         if (count == 1)
         {
             this.Hide();
             Form newForm = new Form();// create new form
             newForm.Show();//display newform
         }
         if (count > 1)
         {
             MessageBox.Show("Duplicate UserName and Password");
         }
         else
         {
             MessageBox.Show("Incorrect UserName and Password");
         }
         connection.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
}

Upvotes: 0

Views: 97

Answers (1)

Marco
Marco

Reputation: 23945

If all you want is the number of rows returned, you should use SELECT COUNT(*) and ExecuteScalar:

command.CommandText = "select Count(*) from login where UserName= @Username and Password= @Password";
command.Parameters.AddWithValue("@Username", userTextBox.Text);
command.Parameters.AddWithValue("@Password", passwordTextBOx.Text);

OleDbDataReader reader = command.ExecuteScalar();

while (reader.Read())
{       
    count = reader.GetInt32(0);
}

Please note, that OleDb does not support named parameters. So while I named them @Username / @Password, these are in fact just placeholders. OleDb only uses positional parameters, so the order in which you add them to your query is important. Adding the password first, will give you a wrong result.

Upvotes: 4

Related Questions