Hi,
Following is a modified version of your code to suit your needs:
1) Move the counter to a global level of the form.
2) You can use 'HasRows' of the data reader to see if a match was found.
int count = 1;
private void button1_Click(object sender, EventArgs e)
{
if (txtuser.Text == "" && txtpass.Text == "")
{
MessageBox.Show("USERNAME and PASSWORD cannot be blank");
txtuser.Focus();
}
else
{
SqlConnection cn = new SqlConnection("Data Source=LAPTOP-SO38VH6F;Initial Catalog=CRMS;Integrated Security=True");
cn.Open();
SqlCommand cmd = new SqlCommand("select * from login where username = '" + txtuser.Text + "' and password = '" + txtpass.Text + "'", cn);
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
MessageBox.Show("WELCOME!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
cn.Close();
Home h = new Home();
h.Show();
this.Hide();
}
else
{
if (count++ >= 3)
{
MessageBox.Show("Failed in 3 login attempts. Assuming unauthorized access. Terminating!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
MessageBox.Show("Wrong Username or Password", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
cn.Close();
txtuser.Clear();
txtpass.Clear();
}
}
}
Some suggestions on improving the code:
1) Wrap in TRY-CATCH.
2) It looks like you are storing the password as is in database. Please use encryption to store and retrieve.
3) Mind Sql Injections. Better pass the username and password to a SQL stored procedure or function that will return YES/NO.