I am attempting to set a login attempt limit. The code allows me to log in to each user, recognizes and invalid attempt, and records the first attempt. BUT it doesn’t add up the attempts and then execute the limitation. I originally had the login types as "else if" statements but it would only approve the last login type. Here is my code. Any hints would be greatly appreciated.
private void buttonLogin_Click(object sender, EventArgs e)
{
MyDB db = new MyDB();
int attempt = 1;
if (attempt < 4)
{
MySqlDataAdapter adapter = new MySqlDataAdapter();
DataTable table = new DataTable();
MySqlCommand command = new MySqlCommand("SELECT * FROM `users` WHERE `username` = @usn AND `password` = @pas", db.getConnection);
command.Parameters.Add("@usn", MySqlDbType.VarChar).Value = textUsername.Text;
command.Parameters.Add("@pas", MySqlDbType.VarChar).Value = textBoxPass.Text;
adapter.SelectCommand = command;
adapter.Fill(table);
if (table.Rows.Count > 0)
{
switch (table.Rows[0]["type"] as string)
{
case "student":
{
this.Hide();
new StudentMain().Show();
break;
}
case "faculty":
{
this.Hide();
new FacultyMain().Show();
break;
}
case "admin":
{
this.Hide();
new AdminMain().Show();
break;
}
}
}
else
{
MessageBox.Show("Invalid Username or Password", "Attempt: " + attempt, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else if (attempt == 4)
{
MessageBox.Show("Login attempts exceeded.");
textUsername.Enabled = false;
textBoxPassword.Enabled = false;
this.Close();
}
attempt++;
}
}
}
>Solution :
It’s because you keep resetting your login attempts each time you click the login button.
Changes this:
private void buttonLogin_Click(object sender, EventArgs e)
{
...
int attempt = 1;
...
}
To this:
int attempt = 1;
private void buttonLogin_Click(object sender, EventArgs e)
{
...
}