---
title: "Login Form in ASP.Net"  
description: "Login form of a designing include a login page where user provides their credential (as shown above). After successful login user will be redirected t"  
author: "Anonymous User"  
published: 2011-01-21  
updated: 2019-10-24  
canonical: https://www.mindstick.com/articles/333/login-form-in-asp-dot-net  
category: "asp.net"  
tags: ["asp.net"]  
reading_time: 5 minutes  

---

# Login Form in ASP.Net

![Login form in ASP.Net](https://www.mindstick.com/mindstickarticle/c389febe-fceb-4cb9-a4d1-41259346f449/images/4420f710-7f2e-49e1-ac1c-5e65f29a9550.png)\

##### Design View of Login Form

Login form of a designing include a login page where user provides their credential (as shown above). After successful login user will be redirected to sign out page which will be displayed after sign in.

##### Design Source for Login Page

```
<body style="height: 452px"><form id="form1" runat="server"><asp:Login ID="Login1" runat="server" BackColor="#F7F6F3" BorderColor="#E6E2D8"BorderPadding="4"  BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana"Font-Size="Large"  ForeColor="#333333" onauthenticate="Login1_Authenticate"style="margin-left: 389px;  margin-top: 141px"><InstructionTextStyle  Font-Italic="True" ForeColor="Black" /><LoginButtonStyle  BackColor="#FFFBFF" BorderColor="#CCCCCC" BorderStyle="Solid"BorderWidth="1px"  Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284775" /><TextBoxStyle Font-Size="0.8em" /><TitleTextStyle BackColor="#5D7B9D" Font-Bold="True" Font-Size="0.9em"ForeColor="White" /></asp:Login></form>
```

##### Screen shot of the above source

![Login form in ASP.Net](https://www.mindstick.com/mindstickarticle/c389febe-fceb-4cb9-a4d1-41259346f449/images/4420f710-7f2e-49e1-ac1c-5e65f29a9550.png)

##### ASP.NET code for login page(LoginPage.aspx.cs)

```
protected void  Login1_Authenticate(objectsender, AuthenticateEventArgse)    {//This condition check that the user who wants to login as administrator or //superadministrator.With the help of substring we check whether user is //administrator or super administrator.          if (Login1.UserName.Substring(0, 1).Equals("A"))        {              //Code to check details of administrator//if user is administrator then checkAdminDetails() method is called which returns a//Boolean value that is either true or false.true value represents user id or //password is correct and false value represents user id and password is incorrect.              if (checkAdminDetails(Login1.UserName, Login1.Password))            {//If user login successful then count value should be zero.                 count =0;                  //create a session variable which store userName                  //create a session variable which store login status.                  createUserName();                  Response.Redirect("SuperAdministrator/UserPage.aspx");            }              else            {//if login attempt is unsuccessful then we increment the value of count.The maximum//attempt for login is 3                count++;                  if (count>3)                {//if login attempt is greater than 3 then a message is displayed and after displaying//message browser should be close.                      Response.Write("<script>alert(''Unauthorized User.Access Is Aborted.');</script>");//code for closing the browser.                      Response.Write("<script>window.close()</script>");                }                  else                {//Other wise a message displayed.Invalid user id or password                      Response.Write("<script>alert('Invalid User Id Or Password.');</script>");                }            }        }          else              if (Login1.UserName.Substring(0, 1).Equals("S"))            {                  //code to check details of super administrator.                  if (checkSuperAdmin(Login1.UserName, Login1.Password))                {                     count =0;                      //create a session variable which store user name                      //create a session variable which store login status.                      createUserName();                      Response.Redirect("SuperAdministrator/Admin.aspx");                }                  else                {//if login attempt is unsuccessful then we increment the value of count.The maximum//attempt for login is                     count++;                      if (count>3)                    {                          Response.Write("<script>alert('Unauthorized User.Access Is Aborted.')</script>");//code for closing the browser                          Response.Write("<script>window.close()</script>");                    }                      else                    {//Other wise a message displayed.Invalid user id or password                          Response.Write("<script>alert('Invalid User Id Or Password.');</script>");                    }                }            }              else            {                  Response.Write("<script>alert('Login Id Does Not Exists.')</script>");            }    }  //count is an static variable which is shared by all page objects which is created by //server.static int count=0;    //createUserName() method is used to store the name of the user is //Session[“userName”] variable.If Session[“userName”] variable contains null then it //means user is not login and he is redirected to login page automaticallypublic void  createUserName()    {          if (Session["userName"] == null)        {             Session["userName"] =Login1.UserName;       }    }  //checkAdminDetails(string userId,string userPassword) is a method which is used to //check administrator creadentialspublic bool  checkAdminDetails(stringuserId, stringuserPassword)    {          bool status=false;//A SqlConnection object is created.Connection String is stored in web.config file //and which is retrived with the help of ConfigurationManager class.           SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["cs"].ConnectionString);//Connection with the appropriate server is opened.         con.Open();//A SqlCommand object is created.When we create SqlCommand object the its constructor //takes two parameter.First parameter represents the query or procedure which needs //to be executed while second parameters represent connection object          SqlCommand cmd=new SqlCommand("checkLoginId", con);//Here we tell the type of query that it is text or stored procedure.          cmd.CommandType=CommandType.StoredProcedure;//Here we created parametrized procedure that’s why we have to add parameters.When we//create object of SqlParameter class its constructor takes two parameter first //parameter represents name of the parameter and second parameters represent the //value of the parameter.          cmd.Parameters.Add(new SqlParameter("@loginId", userId));          cmd.Parameters.Add(new SqlParameter("@password", userPassword));//Here we create the object of SqlDataReader object which contains result sets of the //query          SqlDataReader dr=cmd.ExecuteReader();//if SqlDataReader object contains any row then status should be true.means user is //authenticated otherwise false.          if (dr.Read())        {             status=true;        }          else        {             status=false;        }          return status;    }//checkSuperAdmin(string username,string userPassword) is used to validate the //creadential of super administrator.It returns a Boolean value that is either true //or false.If it returns true then user is authenticated otherwise user is not //authenticatedpublic bool  checkSuperAdmin(stringuserName, stringuserPassword)    {          bool status=false;          if (userName.Equals("S0001") &&userPassword.Equals("admin"))        {             status=true;        }          else        {             status=false;        }          return status;    }
```

Once the user is login we have to design a redirected page.

##### Screen Shot of Redirected Page

![Login form in ASP.Net](https://www.mindstick.com/mindstickarticle/c389febe-fceb-4cb9-a4d1-41259346f449/images/2b5a0dea-4e1c-43a8-873b-76ef86bebbb5.png)

If you want that after log out user can not retrieve pages from browser cache until he logged in the write down the following code at the end of Page_PreInit() event.

```
protected void Page_PreInit(objectsender,  EventArgse)    {         Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));         Response.Cache.SetCacheability(HttpCacheability.NoCache);         Response.Cache.SetNoStore();    }
```

When user press the log out button then all the session information is cleared. And he returns back to the loginPage.

##### Sorce Code For Log Out

```
//when user click the log out button then Session[“userName”] variable contains null //value which means user is log out.And we finnaly call the loginPage again.protected void btnLogOut_Click(objectsender,  EventArgse)    {         Session["userName"] =null;         Response.Redirect("../LoginPage.aspx");    }
```

## \

## \

---

Original Source: https://www.mindstick.com/articles/333/login-form-in-asp-dot-net

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
