I am making a login system using C#, which successfully checks if the user's credentials match up, but for some reason, whenever I write a username that is not the newest record, it gives me the "Username doesn't exist" error, but if it is written with the correct password, it still logs in.
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "Data source=(local);Initial Catalog=GameStore;Integrated Security=True";
conn.Open();
SqlCommand command = new SqlCommand("SELECT * FROM Staff", conn);
//Username
String TextBoxUsername = textBox1.Text;
//Lower Casing
TextBoxUsername = TextBoxUsername.ToLower();
//Password
String TextBoxPassword = textBox2.Text;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//Username
string DatabaseUsername = (string)reader["StaffUserName"];
//Lower Casing
DatabaseUsername = DatabaseUsername.ToLower();
//Password
string DatabasePassword = (string)reader["StaffPassword"];
//If Username Matches One In DB
if (DatabaseUsername == TextBoxUsername)
{
WarningLabel.Visible = false;
WarningLabel.Text = "";
//If Password Matches One In DB
if(DatabasePassword == TextBoxPassword)
{
WarningLabel.Visible = false;
WarningLabel.Text = "";
MessageBox.Show("Logging In");
}
//Wrong Password
else
{
WarningLabel.Visible = true;
WarningLabel.Text = "Incorrect Password";
}
}
//Username doesn't exist in DB
else
{
WarningLabel.Visible = true;
WarningLabel.Text = "Username doesn't exist";
}
}
}
}
}
Yeah that's cause you are doing a select * ...
and storing the data in same string
variable which overwrites all the data and obviously remains with the last record and thus the behavior
while (reader.Read())
{
//Username
string DatabaseUsername = (string)reader["StaffUserName"];
Better would be filter the record based on your input like below and then your posted code should work fine
select * from stuff
where StaffUserName = @uname
and StaffPassword = @pwd;