-5

I have in the DB Sid and password and it contain the Sid=senan and the password=pass1234 when I enter this details into my login screen always I get fail messagebox

SqlDataAdapter cmd = new SqlDataAdapter("select Count(*) from [user] where Sid=' " + textBox1.Text + " ' and password='" + textBox2.Text + "'", cnn);
DataTable dt = new DataTable();
cmd.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
    MessageBox.Show("pass");
else
    MessageBox.Show("fail");
Steve
  • 213,761
  • 22
  • 232
  • 286

1 Answers1

0

The error arises from a simple typo. You have spaces added to the value passed for the Sid condition.
However your query should be rewritten in this way

string cmdText = "select Count(*) from [user] where Sid=@sid and password=@pwd";
SqlCommand cmd = new SqlCommand(cmdText, cnn)
cmd.Parameters.AddWithValue("@sid", textBox1.Text);
cmd.Parameters.AddWithValue("@pwd", textBox2.Text);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
    MessageBox.Show("pass");
else
    MessageBox.Show("fail");

This approach uses a parameterized query to avoid Sql Injection, and uses directly an SqlCommand without building the SqlDataAdapter and a DataTable. The SqlCommand.ExecuteScalar is the correct method to use when you need to retrieve simply the first column of a single row or call a scalar T-SQL function like COUNT()

As a side note, keep in mind that storing passwords in clear text in your database is a big security concern. Whoever has access to the database will be able to read the passwords of every user. The passwords should be stored as a computed hash and checked repeating the hashing algorithm on the user entered data.

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286