Wes is right! if the passwords match the session is set because that is the first line of code after the "if(passord==....)" But the ResponseRedirect is hit every time.
try to
if (password == TextBox2.Text)
{
Session["name"] = TextBox1.Text;
Response.Redirect("AfterLogin.aspx?Name="+TextBox1.Text);
}
If you had attached the debugger you would have seen this behavior. You would probably seen it if your code was a little cleaner also. Hit CTRL+K D to format your code in VS.
Another thing with your code is that you are doing 2 ExecuteScalar(). You only need one. I have rewritten your code in a slightly cleaner way:
protected void Button1_Click(object sender, EventArgs e)
{
string username = Textbox1.Text;
string password = TextBox2.Text;
SqlConnection conn = new SqlConnection("ConnectionString");
string sql = "select password from Reg where UserName=@Username";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@Username", username);
conn.Open();
string pwdFromDb = Convert.ToString(cmd.ExecuteScalar());
cmd.Dispose();
conn.Close();
if(pwdFromDb == password)
{
Session["name"] = username;
Response.Redirect("AfterLogin.aspx?Name=" + username);
}
else
{
Label2.Visible = true;
Label2.Text = "invalid username or password";
}
}
A few tips for you:
1) Always use command parameters when sending variables in your sql!
2) Use brackets around your if's if(){...}
3) Never store passwords as clear text. Hash it and use a password salt.
for (int i = 4; i < 1000; i++)
{
Console.WriteLine(i + ") ALWAYS use command parameters!");
}