1

Initially I set both columns, username and pass, in my database(SQL Server 2012) as int in the employeeinfo table. When I entered the correct credentials, I was able to log in successfully.

However, when I changed both both columns, username and pass, to varchar(50) and entered the correct credentials, I get a message indicating username and password were incorrect.

Any idea why? Code posted below.

private void loginbutton_Click(object sender, RoutedEventArgs e)
{
    SqlConnection con = new SqlConnection(ConString);
    try
    {
        con.Open();
        string query = "select * from employeeinfo where username='" +
            this.txt_username.Text + "' and pass=' " + 
            this.txt_password.Password +"' ";
        SqlCommand cmd = new SqlCommand(query, con);

        cmd.ExecuteNonQuery();
        SqlDataReader dr =  cmd.ExecuteReader();

        int count = 0;
        while (dr.Read())
        {
            count++;
        }
        if (count == 1)
        {
            MessageBox.Show("Open Sesame!");
            second sec = new second();
            sec.ShowDialog();
        }
        if (count > 1)
        {
            MessageBox.Show("Note to developer: Enforce unique constraints!");
        }
        if (count < 1)
        {
            MessageBox.Show("Username and password is not correct. Please try again!");
        }

    }
    catch (Exception ex)
    {

        MessageBox.Show(ex.Message);
    }
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Rich
  • 11
  • 2

2 Answers2

2

Try use parameters :

        cmd.CommandText = "select * from employeeinfo where username=@username and pass=@pass ";
        cmd.Parameters.Add("@username", SqlDbType.VarChar);
        cmd.Parameters["@username"].Value = this.txt_username.Text;
        cmd.Parameters.Add("@pass", SqlDbType.VarChar);
        cmd.Parameters["@pass"].Value = this.txt_password.Password;
        SqlDataReader sdr = cmd.ExecuteReader();
mnshahab
  • 770
  • 7
  • 16
1

In this line you have an extra space after pass=':

string query = "select * from employeeinfo where username='"
   + this.txt_username.Text + "' and pass=' " + this.txt_password.Password +"' ";

Here is the fixed line.

string query = "select * from employeeinfo where username='"
   + this.txt_username.Text + "' and pass='" + this.txt_password.Password + "' ";

It wouldn't hurt to store your passwords more securely (hashed, not plaintext) and learn a bit about SQL injection, though. :)

Blue Ice
  • 7,888
  • 6
  • 32
  • 52