简体   繁体   中英

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).

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM