Click here to Skip to main content
Click here to Skip to main content

How to implement Two basics uses for the Login control 2.0 (login and RememberMe)

, 23 Nov 2006
Rate this:
Please Sign up or sign in to vote.
This article will show you how to implement two basics uses of the ASP.NET Login control (2.0), The login task itself to validate the users who’s trying to access your web site. In addition i will show how to implement the REMEMBERME process using cookies to save the user name inside the user PC


The login control is a good gift to save time in the way to make one of the most important tasks everytime that you developed a site, the login task (Who’s inside, Who’s outside)  Inside the next lines I will try give you a basic, but functional login control programming, which one you can use in your project.


The end of this program is to show the login page first (there is the login control) the user insert their login credentials (username, password) the page evaluates the credentials against a database, if the user exist and the password is the same saved onto database, the login page grant the access to welcome page, at negative case the login page is refresh showing a Login error message and set ready to attempt again.



Sample screenshot


Figure 1. The login process



First Step.

Start a new Project.

Start creating two forms, the login form and the welcome form (destination form).


*Login Form (login.aspx)

*Welcome Form (welcome.aspx)


Forms Controls.


Login Form (login.aspx)

Add the Login Control. (Logeo)


Welcome Form (welcome.aspx)

Add a label (Message)


Now let’s focus on login Control (named Logeo at this example)


If you want to change the default skin check the image below and click over automatic format>classic in order to change to windows XP skin.



Sample screenshot


Figure 2. The login control skin wizard.



That was a Skin change; now let’s make the logical changes to use the login control.

Keep all the properties by default, and change this one.


DestinationPageUrl  = welcome.aspx       At login true case goes to welcome.aspx

Be sure that the authenticated property is false (Login control).



Now let’s validate the user credentials wrote inside the textboxes, true case goes to the URL wrote on DestinationPageUrl property, false case reload the form.


This code on Login control authenticate process evaluates the users credentials and grant or deny the access to the destination page.



protected void Logeo_Authenticate(object sender, AuthenticateEventArgs e)
            string id_user = Logeo.UserName.Trim(); //Get the username from the control
            string pass_user = Logeo.Password.Trim(); //get the Password from the control


 //These are a sql and connection Examples

 string sql = "SELECT coduser, nameuser FROM users WHERE iduser = @param_Id AND passuser = @param_Password";
            public SqlConnection conexionExpress = new SqlConnection("server='localhost\\SQLExpress';Integrated Security=true;Initial Catalog=college;User Instance=false"); //Create the server connection

            SqlCommand comandoSql = new SqlCommand(sql, conexionExpress); //Create the sql command using sql string and sql connection

//Add the sql parameters

  comandoSql.Parameters.AddWithValue("@param_Id", id_user); //New on VS 2.0

  comandoSql.Parameters.AddWithValue("@param_Password", pass_user);

            string cod_user = "";
            string name_user = "";
            //Open database connection
            SqlDataReader dr = comandoSql.ExecuteReader();
            while (dr.Read())
                cod_user = dr.GetValue(0).ToString(); //The coduser is unique onto database table
                name_user = dr.GetValue(1).ToString();
            conexionExpress.Close();//Close Database Connection
            if (cod_user != "") //The user exist onto database
                /*Create the session vars
                Session["coduser"] = cod_user;
                Session["nameuser"] = name_user;
                e.Authenticated = true; //Grant the access, Goes to DestinationPageUrl
        catch(Exception)//On Login Error
            e.Authenticated = false;//Confirm that you are out

  conexionExpress.Close();//On any error case, close the database connection


Now we will change the welcome page to show the user name who grant the access


On welcome.aspx modify the load event


protected void Page_Load(object sender, EventArgs e)


        if (!IsPostBack)


            Message.Text = "Welcome " + Session["nameuser"].ToString() + " Your user code is " +  Session["coduser"].ToString();




At this point you already do the login event in you website, but we have a problem, ¿what happened if the user write the absolute url to welcome page?, he will reach the page, so lets add these lines at web.config file in order to redirect all the attempts to visit forms using absolute urls to login form.


Change the authentication mode to Forms and add the next in order to lock your site, and last define the login form URL like the default form.



<authentication mode="Forms">

<forms loginUrl="login.aspx" protection="All" defaultUrl="login.spx">




To prevent that anonymous users try to access our site, we have to modify the authorization element over the web.config file.



     <deny users=?/>



We these previous lines we are denying the access to all anonymous users.




Sample screenshot


Figure 3. There is only one way to go inside your website, thats the login form



Right now we fulfilled the objectives, all the attempts to get any form inside our website are redirect to login form, and only the registered user can go trough this form.


Now lets implement the remember me next time process in order to save the username inside a cookie, and everytime that the user load the login pagem we can read the username from the cookie.


Here the logical process


Sample screenshot


Figure 4. logical process to read and Create cookies over the pc client.


You can see in the previous picture that the first process to implement is read the cookie from the user PC, if it exist (cookie) read the cookie and write the username parameter inside the login control username textbox.


Here process must to be implement onload process (login.aspx).


protected void Page_Load(object sender, EventArgs e)


       if (!IsPostBack)//On first time


            if (Request.Cookies["myCookie"] != null) //Cookie Exists??


                HttpCookie cookie = Request.Cookies.Get(myCookie");

                string user = cookie.Values["user"].ToString();

                if (user != "")


                    Logeo.UserName = user; //Write the username onto login username textbox 






Already the read cookie process, now we have to implement the other task, write the user name to the cookie.



Sample screenshot


Figure 5. Remember check the box.



When you press the login button a logged in process is fired up, we must to write the create process synthax for the cookie at this time, check the next code lines.


protected void Logeo_LoggedIn(object sender, EventArgs e)


      CheckBox chBox = (CheckBox)Logeo.FindControl("RememberMe");

      if (chBox.Checked)


          HttpCookie myCookie = new HttpCookie("myCookie"); //Instance the new cookie

          Response.Cookies.Remove("myCookie"); //Remove previous cookie

          Response.Cookies.Add(myCookie); //Create the new cookie

          myCookie.Values.Add("user", this.Logeo.UserName); //Add the username field to the cookie

          DateTime deathDate = DateTime.Now.AddDays(15); //Days of life

          Response.Cookies["myCookie"].Expires = deathDate; //Assign the life period


          myCookie.Values.Add("pass", this.Logeo.Password);




That was the implementation for remember me next time feature using cookies to save onto the user pc, be carefully with all the information that you save there. Because an experienced user could read it.



There are more and complicated ways to login registered users, so this is one of the most basics and easy to implement login tasks, enjoy it.

This task look hard but you can do it as easy as you want, feel Free to make any changes.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Britney S. Morales
Web Developer
Colombia Colombia
Web Developer during 3 years and counting, i worked over my school website by two years, right now im webmaster at World Wowan foundation banking in my home city.

Please forgive my pictures examples, they are at spanish language because its my mother language.

Comments and Discussions

QuestionCode file not found Pinmembertahirgr8_20007-Jul-14 20:58 
QuestionHi Pingrouppagani zonda21-Oct-13 21:44 
GeneralMy vote of 5 PinmemberHeaven202017-Mar-13 6:40 
GeneralMy vote of 2 PinmemberMarco Bertschi6-Feb-13 5:00 
QuestionGood Example PinmemberAlireza_13622-Oct-12 5:11 
GeneralNeed Code for Login control with Remember me option in VB.NET Pinmembersaleforu14-Jul-09 8:52 
GeneralMy vote of 1 Pinmembersnorkie11-Jan-09 16:30 
GeneralDynamically Breadcrumb bar Pinmemberkkpaliwal13-Jun-08 4:08 
GeneralRe: Dynamically Breadcrumb bar PinmemberBritney S. Morales13-Jun-08 5:21 
GeneralComentario PinmemberMember 249133916-Apr-08 4:53 
GeneralRe: Comentario PinmemberBritney S. Morales13-Jun-08 5:23 
GeneralRe: Comentario GuruKool1-Oct-08 1:24 
QuestionCant make the C# version works PinmemberJohn Kh14-Apr-08 22:45 
AnswerRe: Cant make the C# version works PinmemberBritney S. Morales13-Jun-08 5:24 
GeneralAbout you and your code PinmemberDobaria Neerav1-Apr-08 9:06 
GeneralRe: About you and your code PinmemberBritney S. Morales1-Apr-08 14:31 
QuestionLogin for ASP.Net PinmemberMember 106126828-Feb-08 20:44 
AnswerRe: Login for ASP.Net PinmemberBritney S. Morales13-Jun-08 5:27 
GeneralHi, Pinmembersdev26-Feb-08 7:57 
QuestionPassword cannot be assigned to -- it is read only Pinmemberpinxu9-Oct-07 23:06 
AnswerRe: Password cannot be assigned to -- it is read only PinmemberSrikanthSapa21-Apr-10 2:30 
Generalavoid encrypted url PinmemberEdward1115-Oct-07 8:50 
GeneralLocalized version of login control Pinmembervdhguy4-Oct-07 23:39 
GeneralRemember Me problem PinmemberMaverickAjith4-Oct-07 1:52 
GeneralBrowser Closed event Pinmemberteeboss3-Oct-07 5:10 
QuestionA lil help pls Pinmemberteeboss28-Sep-07 21:41 
AnswerRe: A lil help pls [modified] PinmemberBritney S. Morales29-Sep-07 5:10 
GeneralRe: A lil help pls Pinmemberteeboss30-Sep-07 0:01 
GeneralRe: A lil help pls(....) PinmemberAswattha16-Dec-08 20:04 
Generalproblem..plz help PinmemberSujit Mandal.28-Sep-07 0:00 
GeneralRe: problem..plz help PinmemberBritney S. Morales28-Sep-07 3:28 
Generalvery good article PinmemberSujit Mandal.27-Sep-07 23:14 
GeneralRe: very good article PinmemberBritney S. Morales28-Sep-07 3:36 
QuestionSQL table design? Pinmemberdarkknight123421-Sep-07 11:10 
AnswerRe: SQL table design? PinmemberBritney S. Morales28-Sep-07 3:46 
GeneralRe: SQL table design? Pinmemberdarkknight123428-Sep-07 3:59 
Generalnice article... Pinmemberjaiminpatel96313-Sep-07 1:21 
GeneralRe: nice article... PinmemberBritney S. Morales28-Sep-07 3:52 
GeneralThank you! PinmemberG.Stanley John28-Aug-07 21:46 
GeneralRe: Thank you! PinmemberBritney S. Morales28-Sep-07 3:52 
GeneralHI Pinmembermaram20002-Aug-07 15:47 
GeneralRe: HI PinmemberBritney S. Morales3-Aug-07 4:06 
GeneralHelp me Pinmembermaram20002-Aug-07 15:40 
in this cood i use AccessDB i want to use SQLDB how i can transfer this cood using SQLDB??????please help me

Public Class addnewcontent
Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.
Private Sub InitializeComponent()

End Sub
Protected WithEvents Label1 As System.Web.UI.WebControls.Label
Protected WithEvents Label2 As System.Web.UI.WebControls.Label
Protected WithEvents Label3 As System.Web.UI.WebControls.Label
Protected WithEvents Button1 As System.Web.UI.WebControls.Button
Protected WithEvents Button2 As System.Web.UI.WebControls.Button
Protected WithEvents txtTitle As System.Web.UI.WebControls.TextBox
Protected WithEvents txtContent As System.Web.UI.WebControls.TextBox
Protected WithEvents lblMsg As System.Web.UI.WebControls.Label
Protected WithEvents HyperLink1 As System.Web.UI.WebControls.HyperLink

'NOTE: The following placeholder declaration is required by the Web Form Designer.
'Do not delete or move it.
Private designerPlaceholderDeclaration As System.Object

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
End Sub

#End Region

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
If Request.QueryString("id") <> "" And Not IsPostBack() Then
Dim cn As New OleDb.OleDbConnection
Dim cm As New OleDb.OleDbCommand
Dim dr As OleDb.OleDbDataReader

cn.ConnectionString = ConfigurationSettings.AppSettings("ConnectionString")
cm.Connection = cn
cm.CommandText = "Select * From Content Where id=" & Request.QueryString("id")
dr = cm.ExecuteReader()
txtTitle.Text = dr.GetValue(1)
txtContent.Text = dr.GetValue(2)

Catch ex As Exception
lblMsg.Text = ex.Message
End Try

End If
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cn As New OleDb.OleDbConnection
Dim cm As New OleDb.OleDbCommand
Dim title As String = txtTitle.Text
Dim content As String = txtContent.Text

cn.ConnectionString = "Provider=Microsoft.JET.OLEDB.4.0; Data Source=C:\Inetpub\wwwroot\ASPNETDBAdminControl\database\data.mdb"
cm.Connection = cn
If Request.QueryString("id") <> "" Then
cm.CommandText = "Update Content Set Title='" & title & "', content='" & content & "' " _
& "Where id=" & Request.QueryString("id")
lblMsg.Text = "Content Record is updated successfully"
cm.CommandText = "Insert Into Content (title,content)" _
& " Values('" & title & "','" & content & "')"
lblMsg.Text = "Content Record is inserted successfully"
End If

Catch ex As Exception
lblMsg.Text = ex.Message
End Try

End Sub
End Class


GeneralRe: Help me PinmemberBritney S. Morales3-Aug-07 4:02 
GeneralHola qué tal ! PinmemberJulioDeLeon23-Jul-07 12:15 
GeneralRe: Hola qué tal ! PinmemberBritney S. Morales24-Jul-07 4:05 
GeneralRe: Hola qué tal ! PinmemberJulioDeLeon24-Jul-07 16:10 
GeneralHi Pinmemberar_monti10-Jul-07 3:21 
GeneralRe: Hi PinmemberBritney S. Morales10-Jul-07 4:25 
GeneralWorth reading PinmemberSMKarten16-Mar-07 11:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150331.1 | Last Updated 23 Nov 2006
Article Copyright 2006 by Britney S. Morales
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid