I'm trying to make a login webpage, and for some reason its always gets into the "false" line where login and password are incorrect. I checked in the database to see maybe I'm a douche, but this is completely true.
This is my code :
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
string query = "SELECT Username, Password FROM Users WHERE Username='" + Username + "' AND Password='" + Password + "'";
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter adap = new SqlDataAdapter(query, con);
adap.Fill(ds);
int count = ds.Tables[0].Rows.Count;
if (count == 0)
{
ErrorMessege.Text = "Username or Password was Incorrect!";
}
else
{
Session["Session"] = UsernameLogin.Text;
Response.Redirect("MenuHome.aspx");
}
con.Close();
Thanks for the helpers!
Your code looks like it should work. Have you stepped through it and added a watch on ds to see what values it has? I executed the code on my machine against one of my test DBs and it worked fine.
I would however suggest something similair to this as it is a lot cleaner in my opinion:
using(SqlConnection con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True"))
{
string query = "SELECT TOP 1 Username FROM Users WHERE Username=@UserName AND Password=@Password";
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("@UserName", UserName);
command.Parameters.AddWithValue("@Password", Password);
con.Open();
string username = (string)command.ExecuteScalar(); //Add Null Check
// Do stuff if username exists
}
}
You should always add a using statement on an object that implements IDisposable.(SqlConnection, SqlCommand) Also to prevent SqlInjection and the likes, use parameterized queries.