Reputation: 5962
i want to implement the functionality of remember me in my login
page.for this purpose i have used cookies. it is working fine but when login and logout twice , then after try to login for the same username and password, it shows invalid username and password.
code for login page
protected void Page_Load(object sender, EventArgs e)
{
lblStatus.Visible = false;
if(Request.Cookies["temp"] != null)
{
txtUsername.Text = Request.Cookies["temp"].Values["u"];
txtPassword.Text = Request.Cookies["temp"].Values["p"];
}
}
protected void btnLogn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(str);
con.Open();
string username = txtUsername.Text;
string password = txtPassword.Text;
SqlCommand cmd = new SqlCommand("select username from Login where username='"+username+"' AND password='"+password+"'",con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
HttpCookie ht = new HttpCookie("temp");
if(CheckBox1.Checked)
{
ht.Values["u"] = txtUsername.Text;
ht.Values["p"] = txtPassword.Text;
Response.Cookies.Add(ht);
Response.Redirect("Home.aspx");
}
else
{
if (Request.Cookies["temp"] != null)
{
ht.Values["u"] = "";
ht.Values["p"] = "";
Response.Cookies.Add(ht);
}
Response.Redirect("Home.aspx");
}
}
else
{
lblStatus.Visible = true;
lblStatus.Text = "Invalid username or Password";
lblStatus.ForeColor = Color.Red;
}
}
code for home page where i have only a single button(Logout)
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogout_Click(object sender, EventArgs e)
{
Response.Redirect("Login.aspx");
}
Upvotes: 0
Views: 143
Reputation: 6903
Check PostBack in your page load as follows
protected void Page_Load(object sender, EventArgs e)
{
lblStatus.Visible = false;
if(!Page.IsPostBack)
{
if(Request.Cookies["temp"] != null)
{
txtUsername.Text = Request.Cookies["temp"].Values["u"];
txtPassword.Text = Request.Cookies["temp"].Values["p"];
}
}
}
In your code after you click the button the old cookie values replace the current values of your textboxes
Upvotes: 1