Menu

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Wednesday, 10 August 2016

How to create a login form in asp.net

Introduction:
 Hi, friends .Here I explained how to create a Login form in asp.net using C# and Sql server that will allow the user to provide his/her credentials without fail to access website/web application which resides on server. And also I applied all client side validations using JavaScript .that restrict the user doesn’t allow to entered any invalid input. So let’s see how we go ahead step by step to achieve this.
Before going to this article please see/visit  how to create registration form in asp.net.
Prerequisites:
  • Must know about the asp.net controls and their use
  • Visual studio IDE-2012/13/15(any edition: Express, ultimate and professional)
  • .Netframework-3.5/4.0/4.5/4.5.1.sqlserver-2008/08sp2/12/14

Database:
Here I used same table which I created in previous article. Let’s create a table named as Register with required fields, if you don’t know how create a table in Database then must see my previous article how to create a table in Sql.
Create Table register
(
          regid int primary key identity(1,1),
          firstname varchar(25),
          lastname varchar(25),
          gender varchar(25),
          email varchar(25),
          password varchar(10),
          phone bigint,
          address varchar(50),
         createddate datetime
)
Go
Design view: Just copy and paste the above code in your query designer, then select all and press f5 or Execute button in menu bar.



Application:
Step1: To create Login page first you need to open visual studio and run as administrator.
Step2: Go to File
Step3: Right click on File and Go to new
Step4: Choose either website or Project
Step5: A new template will be opened
Step6: Choose the language as Visual C# in left side
Step7: Select ASP.NET Empty website in right side.
Step8: Finally, in bottom specify the website is http, ftpsystem or file system
Step9: Choose HTTP,specify the name of the website at http://localhost/yourwebsitename and click on ok.
Step10: if you chosen new project, skip 8 -9 steps and just specify the Solution name and directory enough. You have successfully created.
Step11: Go to Solution Explorer, Right Click on your application and Add new web form named as Login Form.
Design view: Design the form shown below using asp.net controls.

Login.aspx:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Loginform</title>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic,800,800italic' rel='stylesheet' />
    <style type="text/css">
        body {
            font-size: 14px;
            font-family: 'Open Sans', sans-serif;
        }

        th {
            text-align: right;
        }

        .content {
            width: 55%;
            background-color: rgba(33, 150, 243, 0.04);
            margin: 0 auto;
            text-align: center;
        }

        .head {
            background-color: rgba(0, 150, 136, 0.39);
            text-align: center;
            padding: 0.1%;
            width: 57%;
            margin: 0 auto;
        }

        .btnlogin {
            background-color: #DB4437;
            border-style: None;
            padding: 9px;
            border-radius: 9px;
            width: 80px;
            font-size: 16px;
            color: white;
        }

        textarea {
            resize: none;
        }
    </style>
    <script type="text/javascript">

        function validate() {
            if (document.getElementById("<%=txtuname.ClientID%>").value == "") {
                alert("Email/username Field can not be blank");
                document.getElementById("<%=txtuname.ClientID%>").focus();
                return false;
            }
            var emailPat = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            var emailid = document.getElementById("<%=txtuname.ClientID %>").value;
            var matchArray = emailid.match(emailPat);
            if (matchArray == null) {
                alert("Your email address seems incorrect. Please try again.");
                document.getElementById("<%=txtuname.ClientID %>").focus();
                return false;
            }
            if (document.getElementById("<%=txtpwd.ClientID%>").value == "") {
                alert("Password Field can not be blank");
                document.getElementById("<%=txtpwd.ClientID%>").focus();
                return false;
            }
            return true;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">

        <div class="content">
            <div class="head">

                <h3>Login here..
                </h3>

            </div>
            <br />
            <asp:Label ID="lblmsg" runat="server"></asp:Label>
            <table align="center">
                <tr>
                    <th>
                        <asp:Label ID="lblusername" runat="server" Text="Username/Email:" AssociatedControlID="txtuname"></asp:Label>
                    </th>
                    <td>
                        <asp:TextBox ID="txtuname" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <th>
                        <asp:Label ID="lblpwdame" runat="server" Text="Password:" AssociatedControlID="txtpwd"></asp:Label>
                    </th>
                    <td>
                        <asp:TextBox ID="txtpwd" runat="server" TextMode="Password"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <br />
                        <asp:Button ID="btnlogin" runat="server" Text="Submit" CssClass="btnlogin" OnClick="btnlogin_Click" OnClientClick="validate()"></asp:Button>
                    </td>
                </tr>
            </table>
        </div>

    </form>

</body>
</html>

Login.aspx.cs:

using System;
//this namespace required to read Web.config file settings
using System.Configuration;
// this namespace used to access Connection classes
using System.Data;
//this namespace required to access SqlClient classes like SqlCommand,SqlDataReader
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Loginform : System.Web.UI.Page
{
    SqlConnection con;
    protected void Page_Load(object sender, EventArgs e)
    {
        //connection Initialization
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    }

    protected void btnlogin_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtuname.Text.Trim()) && string.IsNullOrEmpty(txtpwd.Text.Trim()))
        {
            lblmsg.Text = "please enter the username and password!!!";
            lblmsg.ForeColor = System.Drawing.Color.Red;
        }
        else
        {

            SqlCommand cmd = new SqlCommand("select Count(*) from register where email =@username and password=@password", con);
            if (con.State != ConnectionState.Open)
                con.Open();
            cmd.Parameters.AddWithValue("@username", txtuname.Text);
            cmd.Parameters.AddWithValue("@password", txtpwd.Text);
            // here I am getting no.of rows with these credentials using that going ahead
            int rowcount = Convert.ToInt32(cmd.ExecuteScalar());
            try
            {

                if (rowcount > 0)
                {
                    Response.Redirect("Default2.aspx");
                }
                else
                {
                    lblmsg.Text = "Invalid Credentials!!!";
                    lblmsg.ForeColor = System.Drawing.Color.Red;
                }


            }
            catch (Exception ex)
            {
                lblmsg.Text = ex.Message;
            }
            finally
            {
                if (con.State != ConnectionState.Closed)
                    con.Close();
                txtuname.Text = txtpwd.Text = "";
            }
        }

    }
}
Output:
To run the page on server Press F5 or cntl+F5.


Step1: Click on submit button, it alerts you to enter all the fields are must.


Step3: Now, Enter all the fields without fail



Step4: Click on submit, Data will be submitted successfully redirects to specified page.

...for more information about previous tutorial please visit this link  ASP.Net Tutorials and
Thank you for visiting my blog ,don't forget to comment on post and if you want daily updates Just  follow me in Google Plus.