i am trying to create a login web form , what i need to show a label if the login fails like " login failed , try again " , but the problem it doesn't work
here 开发者_Python百科is my code:
SqlCommand selectuser = new SqlCommand("select username,password from users where username = '" + TextBox1.Text + "' and password = '" + TextBox2.Text + "'", badersql);
badersql.Open();
SqlDataReader dr = selectuser.ExecuteReader();
while (dr.Read())
{
if (dr["username"].ToString() == TextBox1.Text && dr["password"].ToString() == TextBox2.Text)
{
}
else
{
Label1.Visible = true;
}
}
dr.Close();
Please Note : i know there is NO parametrized SQL In the code, and that because i don't need to use them , all the web page is 100% locally so please help me with issue and leave the sql injections :)
If no results are returned from the database then your link would never be set to visible, because dr.Read() will return false. Which what is happening to you now.
What you need to do, as I believe that your query will always return only one result is to just do
SqlCommand selectuser = new SqlCommand("select username,password from users where username = '" + TextBox1.Text + "' and password = '" + TextBox2.Text + "'", badersql);
SqlDataReader dr = null;
try
{
dr = selectuser.ExecuteReader();
Label1.Visible = !dr.Read();
}
finally
{
if (dr != null)
dr.Close();
}
and you should be done.
now some tips there, you are already doing the filtering in the sql server, so you could just do Select 1 from ...
and do command.ExecuteScalar() != null
If you still want to use a DataReader for other reason, then you should use a try {...} finally { dr.close(); }
block to ensure the datareader is not left open when unhandled error happens.
精彩评论