简体   繁体   中英

If-Else statement not working within a while loop

I have an issue where I'm trying to create a login form, however the else statement seems to be ignored.

How can I write this code extract so that a message box is shown when the incorrect data is put into the text boxes? (All databases are set up correctly).

try
{
    sc.Open();
    SqlDataReader myReader = null;
    SqlCommand myCommand = new SqlCommand("select * from StudentRecords where ID = '" + txtBoxUsername.Text + "' ", sc); //where ID = '" + txtBoxUsername.Text + "' and DOB = '" + textBoxPassword.Text + "'
    myReader = myCommand.ExecuteReader();

    while (myReader.Read())
    {
        if (txtBoxUsername.Text == (myReader["ID"].ToString()) && textBoxPassword.Text == (myReader["DOB"].ToString()))
        {
            LoginSuccessForm loginfrm = new LoginSuccessForm();
            loginfrm.Show();
            this.Hide();
        }
        else if (txtBoxUsername.Text != (myReader["ID"].ToString()) || textBoxPassword.Text != (myReader["DOB"].ToString()))
        {
            MessageBox.Show("Incorrect Password and/or Username", "Error");
            break;
        }

    }
    sc.Close();
}

I have tried putting the messagebox outside of the while loop and that doesn't work in the desired way. (Following the try method is a catch, I didn't include it to save space).

In saying that, it seems to only pick up the first user in the database too. Any clues or guidance would be appreciated!

You don't need to loop through the results, since you're only expecting one row max. I would do it this way:

using (var cmd = sc.CreateCommand()) {
   cmd.CommandText = "select 1 from Students where Username=.. and Password= ..";
   if (cmd.ExecuteScalar() != null) {
      // username and password matched a user
   }
   else {
      // no match 
   }
}

ExecuteScalar returns the first column of the first row, or null if there was no result.

If this was a real project, you'd need to use SqlParameters to avoid SQL injection vulnerabilities and also look at hashing/salting rather than storing plain-text passwords.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM