Google How to create login form/page and implement remember me next time checkbox in | Asp.Net,C#.Net,VB.Net,MVC,jQuery,JavaScipt,AJAX,WCF,Sql Server example

How to create login form/page and implement remember me next time checkbox in

Introduction: In this article i am going to explain How to implement remember me next time checkbox option along with username and password in the Log in form in using both C# and language. Username and password will be stored in the cookie .

remember me next time checkbox option in login form in

Description: The benefits of implementing remember me option is that user needs not to enter the username and password each time to log in, if he wish. This option will maintain the credentials i.e. username and password for the user when he visit the website next time.

In previous related article i explained How to create Login page/form and check username,password in using sql server database and Create registration form and send confirmation email to activate account to new registered users and  Create Change password form/page in using Sql server and Encrypt and decrypt username,password and store in Sql Server database and Create contact us form and Recover and reset the forgot password using activation link in email id and  Check login in by passing parameter to stored procedure in sql server .

The process is as follows: 
  • When user enter username and password and press the login button, the code will first verify the credentials from the Sql server database.
  • If verified then it will further check whether the "remember me next time" checkbox is checked or not. If checked then the username and password will be stored in the cookie for 30 days otherwise it will destroy the cookie by setting the cookie's expiration date to past date. E.g. one day in the past.
  • On page load event we check for the existence of cookie. If exists, username and password will be fetched from the cookie and filled in corresponding TextBox.

Implementation: Let's create a sample website to understand the concept. 
  • In the <form> tag of the design page (.aspx) place two TextBox controls, a CheckBox and a Button control. 

HTML Source Code:

    <fieldset style="width:320px;">
    <legend>Login with remember me option in</legend>   
    <td>UserName : *</td><td>
        <asp:TextBox ID="txtUserName" placeholder="User Name" Width="180px" runat="server"></asp:TextBox><br />
        <asp:RequiredFieldValidator ID="rfvUserName" runat="server"
            ControlToValidate="txtUserName" Display="Dynamic"
            ErrorMessage="Please enter User Name" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
    <td>Password : *</td><td>
        <asp:TextBox ID="txtPwd" placeholder="Password" TextMode="Password" Width="180px" runat="server"></asp:TextBox><br />
        <asp:RequiredFieldValidator ID="rfvPwd" runat="server"
            ControlToValidate="txtPwd" Display="Dynamic"
            ErrorMessage="Please enter Password" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
        <asp:Button ID="btnLogin" runat="server" Text="Login"
            onclick="btnLogin_Click" />
        <asp:CheckBox ID="chkRemember" Text="Remember me next time" runat="server" />

Note: I have also validated the username and password using RequiredFieldValidator validation control so that they can't be left blank.

  • Create a database in Sql server e.g. "MyDataBase" and in this database create a table with the columns and data type as shown below and name it "Tb_Login".

Data Type
Int (Primary Key. So set Is Identity=True
  • Also create a Stored procedure to authenticate the login attempt.

                @UserName  varchar(100),
                @Pwd       varchar(100)
                SELECT UserName,[Password] from Tb_Login
                where UserName COLLATE Latin1_general_CS_AS=@UserName and [Password] COLLATE Latin1_general_CS_AS=@Pwd

Note: In this stored procedure i have also used the COLLATE Latin1_general_CS_AS to check for the exact username and password match because it is used to make the Sql queries case sensitive. e.g. if the username is admin and password is demo then if user enters Admin in username or Demo in password field then it will not match and it the log in attempt will get failed.
  • In the web.config file create the connection string to connect the website with the Sql server database as:

    <add name="conStr" connectionString="Data Source=lalit;Initial Catalog=MyDataBase;Integrated Security=True"/>

NoteReplace the Data Source and Initial catalog (i.e. Database name) as per your application.

Asp.Net C# Code to implement remember me checkbox option in login form
  • In the code behind file (.aspx.cs) write the code as:.

First include the following required namespaces and write the code as:

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

    protected void btnLogin_Click(object sender, EventArgs e)
        SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
        SqlDataAdapter adp = new SqlDataAdapter();
            adp = new SqlDataAdapter("CheckLogin_sp", con);
            adp.SelectCommand.Parameters.AddWithValue("@UserName", txtUserName.Text.Trim());
            adp.SelectCommand.Parameters.AddWithValue("@Pwd", txtPwd.Text.Trim());
            adp.SelectCommand.CommandType = CommandType.StoredProcedure;
            if (con.State == ConnectionState.Closed)
            SqlDataReader dr = adp.SelectCommand.ExecuteReader();

            if (dr.HasRows)
                if (chkRemember.Checked)
                    Response.Cookies["UserName"].Value = txtUserName.Text.Trim();
                    Response.Cookies["Pwd"].Value = txtPwd.Text.Trim();
                    Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(30);
                    Response.Cookies["Pwd"].Expires = DateTime.Now.AddDays(30);       
                    Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies["Pwd"].Expires = DateTime.Now.AddDays(-1);
           ScriptManager.RegisterStartupScript(thisthis.GetType(), "Message""alert('Login Successful');"true);
                ScriptManager.RegisterStartupScript(thisthis.GetType(), "Message""alert('Invalid UserName or Password');"true);
        catch (Exception ex)
            ScriptManager.RegisterStartupScript(thisthis.GetType(), "Message""alert('Error occurred : " + ex.Message.ToString() + "');"true);

protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            if (Request.Cookies["UserName"] != null && Request.Cookies["Pwd"] != null)
                txtUserName.Text = Request.Cookies["UserName"].Value;
                txtPwd.Attributes.Add("value", Request.Cookies["Pwd"].Value);
                chkRemember.Checked = true;

Asp.Net VB Code to implement remember me checkbox option in login form
  • In the code behind file (.aspx.vb) write the code as:

First import the following required namespaces and write the code as:

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

    Protected Sub btnLogin_Click(sender As Object, e As System.EventArgsHandles btnLogin.Click
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
        Dim adp As New SqlDataAdapter()
            adp = New SqlDataAdapter("CheckLogin_sp", con)
            adp.SelectCommand.Parameters.AddWithValue("@UserName", txtUserName.Text.Trim())
            adp.SelectCommand.Parameters.AddWithValue("@Pwd", txtPwd.Text.Trim())
            adp.SelectCommand.CommandType = CommandType.StoredProcedure
            If con.State = ConnectionState.Closed Then
            End If
            Dim dr As SqlDataReader = adp.SelectCommand.ExecuteReader()

            If dr.HasRows Then
                If chkRemember.Checked Then
                    Response.Cookies("UserName").Value = txtUserName.Text.Trim()
                    Response.Cookies("Pwd").Value = txtPwd.Text.Trim()
                    Response.Cookies("UserName").Expires = DateTime.Now.AddDays(30)
                    Response.Cookies("Pwd").Expires = DateTime.Now.AddDays(30)
                    Response.Cookies("UserName").Expires = DateTime.Now.AddDays(-1)
                    Response.Cookies("Pwd").Expires = DateTime.Now.AddDays(-1)
                End If
                    ScriptManager.RegisterStartupScript(MeMe.[GetType](), "Message""alert('Login Successful');"True)

                ScriptManager.RegisterStartupScript(MeMe.[GetType](), "Message""alert('Invalid UserName or Password');"True)
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(MeMe.[GetType](), "Message""alert('Error occurred : " & ex.Message.ToString() & "');"True)
        End Try
    End Sub
Protected Sub Page_Load(sender As Object, e As System.EventArgsHandles Me.Load
        If Not IsPostBack Then
            If Request.Cookies("UserName"IsNot Nothing AndAlso Request.Cookies("Pwd"IsNot Nothing Then
                txtUserName.Text = Request.Cookies("UserName").Value
                txtPwd.Attributes.Add("value", Request.Cookies("Pwd").Value)
                chkRemember.Checked = True
            End If
        End If

    End Sub

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."


  1. Nice and very informative blog....

    1. Thanks for your appreciation Rajesh Deepak..stay tuned and stay connected

  2. I am getting error on line SqlDataReader dr = adp.SelectCommand.ExecuteReader(); that could not found the store procedure.

    Any solution

    1. Hello pratik..have you created the stored procedure "CheckLogin_sp" and connected your sql server database with the Please check and notify me..

  3. Hello sir, this blog is very useful, and thank you very much, but i still have some small doubt like which is the good practice for storing the user credentials like in cookies or database or in web.config file , please clearify me may be with a small practical example when to use to store data in cookies and database and in some other,..! Thank you.

  4. i love this blog

    1. Thanks sanjay..i am glad you found this blog helpful..stay connected and keep reading..:)

  5. Nice work...

    1. Thanks for appreciating my is always nice to hear that my article helped anyone in learning connected and keep reading..:)

  6. Hi,

    Your code is good.
    But if you see, browser by default ask for save password even you don't keep remember me checkbox.
    My question is, if we save using browser save option it save into cookies but it saves plain value. How can I encrypt the same ?

  7. Great and more secure via stored procedure.

    1. Thanks for your valuable feedback Eman Diab..:)

  8. great work. love it

    1. Thanks for appreciating my work..stay connected and keep reading for more useful updates like this..


If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..