[英]I'm validating a form in C# but I don't know what I am doing wrong. Please help me solve this
I'm creating a validation for form data coming from database and then comparing it with data entered in textboxes.我正在为来自数据库的表单数据创建验证,然后将其与在文本框中输入的数据进行比较。 It always executes else part whether I enter correct or incorrect data in textboxes, please help with this.
无论我在文本框中输入正确还是不正确的数据,它总是执行其他部分,请帮助解决这个问题。
c.Uname = Text1.Value.ToString();
c.Cnic = Text2.Value.ToString();
c.pass = Text3.Value.ToString();
SqlConnection sqlConn = new SqlConnection(@"Data Source=DESKTOP-Q4AAHCG;Initial Catalog=practise;User ID=;Password=;Trusted_Connection=True");
SqlCommand sqlComm = new SqlCommand("select Uname , Cnic, password from carregister", sqlConn);
sqlConn.Open();
SqlDataReader dr = sqlComm.ExecuteReader();
while (dr.Read())
{
name = dr["Uname"].ToString();
cnic = dr["Cnic"].ToString();
passs = dr["password"].ToString();
if (name.Equals(c.Uname) && cnic.Equals(c.Cnic) && passs.Equals(c.pass))
{
Session["Uname"] = Text1.Value.ToString();
Session["cnic"] = Text2.Value.ToString();
Response.Redirect("Carloby.aspx");
}
else
{
Response.Redirect("wrongidpass.aspx");
}
}
You are reading ALL rows of your usertable and start comparing with the first received row.您正在读取用户表的所有行并开始与收到的第一行进行比较。 If this doesn't match, you are already redirecting...
如果这不匹配,您已经在重定向...
You could count only the matching rows from your database, and if that returns anything other than 1
, there is an error with username or password (or your database).您可以只计算数据库中匹配的行,如果返回
1
以外的任何内容,则用户名或密码(或您的数据库)存在错误。
c.Uname = Text1.Value.ToString();
c.Cnic = Text2.Value.ToString();
//you don't store plaintext passwords in your db, do you?
c.pass = hash_the_password(Text3.Value.ToString());
SqlConnection sqlConn = new SqlConnection(@"Data Source=DESKTOP-Q4AAHCG;Initial Catalog=practise;User ID=;Password=;Trusted_Connection=True");
SqlCommand sqlComm = new SqlCommand("SELECT COUNT(*) FROM carregister WHERE uname = @uname and cnic = @cnic and password = @hashedpassword", sqlConn);
sqlComm.Parameters.Add("@uname", SqlDbType.NVarchar).Value = c.Uname;
sqlComm.Parameters.Add("@cnic", SqlDbType.NVarchar).Value = c.Cnic;
sqlComm.Parameters.Add("@hashedpassword", SqlDbType.NVarchar).Value = c.pass;
sqlConn.Open();
if (Convert.ToInt32(sqlComm.ExecuteScalar()) == 1) {
//you have exactly one row where uname, cnic and password match the entered values
Session["Uname"] = Text1.Value.ToString();
Session["cnic"] = Text2.Value.ToString();
Response.Redirect("Carloby.aspx");
}
else
{
//no row matched
//(or more than one which is an error in the database, because uname should probably be unique)
Response.Redirect("wrongidpass.aspx");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.