Share via


How to make a user registration and login form in ASP.Net Webforms?

OPEN VISUAL STUDIO 2013
Click On New Project.
On Web, Select ASP.Net empty Web Application
Now right click on solution project and select Add than new item now go to Data option and select the SQL Server Database.
Now the Folder App Data is created in which Database1.mdf file exist. 
Open this file and right click on Tables option and select Add new Table.
Fill the table with specific column names and their Datatypes and name this table as users and add them identity on Primary Key,as show you below image.

Update the table before closing them.
Now right click on solution and select Add than New item and select Web Form name it  UserRegistration.
Now Web Form has been created.
The file with name UserRegistration.aspx is used to create your Html view,and the file name UserRegistration.cs is used for code behind it, ON CLICK  operation.
Now open the UserRegistration.aspx file.
Click on Toolbox and select TextBox for all columns you can also select the Dropdown list for Gender column and for Date Of Birth after taking TextBox select Text Mode Date.
You can also apply proper validations on this form so that incorrect information can not be send.
For this select the Required Field Validator for all TextBox and Dropdown list and write a error message also give Id of that TextBox in which validation is required.
Now if the user enter wrong information than error message will be shown.
Source Code Show you below here:

 <!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     
 
 
    <h2>REGISTER YOUR ACCOUNT</h2>
    <br />
    <br />
     <div> 
        <table style="width: 100%">
            <tr>
                <td style="width: 148px">FirstName :</td>
                <td>
                    <asp:TextBox ID="fname" runat="server" CssClass="highlight" placeholder="First name here.."
                        Height="24px" Width="175px"></asp:TextBox>
                     
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="fname"
                         ErrorMessage="Please enter first name">*</asp:RequiredFieldValidator>
                       <br />
                    <br />
                     
                </td>
            </tr>
             <tr>
                <td style="width: 148px; height: 22px">LastName :</td>
                <td style="height: 22px">
                    <asp:TextBox ID="lname"  runat="server" CssClass="highlight" placeholder="Last name here.."
                        Height="24px" Width="175px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="lname"
                         ErrorMessage="Please enter last name ">*</asp:RequiredFieldValidator>
                    <br />
                    <br />
                </td>
            </tr>
            <tr>
                <td style="width: 148px">Gender  :</td>
                <td>
                    <asp:DropDownList ID="gender_dd" runat="server" CssClass="highlight" Height="24px"  Width="119px">
                        <asp:ListItem Value="" Text="Select One"/>
                        <asp:ListItem>Male</asp:ListItem>
                        <asp:ListItem>Female</asp:ListItem>
                    </asp:DropDownList>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="gender_dd"
                         ErrorMessage="Please select one">*</asp:RequiredFieldValidator>
                    <br />
                    <br />
                </td>
            </tr>
            <tr>
                <td style="width: 148px">DateOfBirth :</td>
                <td>
                    <asp:TextBox ID="date" TextMode="Date" runat="server" CssClass="highlight" Height="24px"  Width="175px"></asp:TextBox>
                    
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="date"
                         ErrorMessage="Please enter your birthday">*</asp:RequiredFieldValidator>
                    
                    <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="date"
                        ErrorMessage="Please enter a valid date" Operator="DataTypeCheck" Type="Date">*</asp:CompareValidator>
                    
                    <br />
                    <br />
                   </td>
                  </tr>
                  <tr>
                <td style="width: 148px">Email_Id :</td>
                <td>
                    <asp:TextBox ID="email"  runat="server" CssClass="highlight" placeholder="Type Email adress .."
                         
                        Height="24px" Width="175px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="email"
                        ErrorMessage="Please enter email_id">*</asp:RequiredFieldValidator>
                    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="email"
      ErrorMessage="enter a valid email" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
                    <br />
                    <br />
                </td>
            </tr>
            <tr>
                <td style="width: 148px">Password :</td>
                <td>
                    <asp:TextBox ID="password" TextMode="Password" runat="server" CssClass="highlight" placeholder="Type password here.."
                         Height="24px" Width="175px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="password"
                        ErrorMessage="Please enter password">*</asp:RequiredFieldValidator>
                    <br />
                    <br />
                </td>
            </tr>
            <tr>
                <td style="width: 148px"> </td>
                <td>
                    <asp:ValidationSummary ID="ValidationSummary1" runat="server" />
                    <br />
                    <asp:Button OnClick="registerBtn_Click1" ID="registerbtn" runat="server" Text="Register" CssClass="link-button red" />
                    <br />
                    <br />
                    <asp:Label ID="outputlabel" runat="server"></asp:Label>
                    <br />
                </td>
            </tr>
        </table></div>
   <h3> <a href="Login.aspx">Login Here!</a></h3>
 
 
 
    </div>
    </form>
</body>
</html>

Now you have to create a connection String.
From Above code after button add also write this code 

<asp:SqlDataSource ID="Sample" runat="server"></asp:SqlDataSource>

Come to Design view and select SqlDataSource than click on Configure Data Source.
Name connection string as DefaultConnectionString click on Next select all from user table click next and than finish.
Now the connection string is established.
The above code will be like after this steps are:

<asp:SqlDataSource ID="Sample" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnectionString %>SelectCommand="SELECT * FROM [Users]"  ></asp:SqlDataSource>

see at Web.config file connection string is automatically  added as

<connectionStrings>
       <add name="DefaultConnectionString" connectionString="Data Source=(LocalDB)\mssqllocaldb;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True"
           providerName="System.Data.SqlClient" />
   </connectionStrings>

 Now run this application but you get the error as:

To solve this error add the Global.aspx file and open them on at application start enter the following code

protected void  Application_Start(object sender, EventArgs e)
       {
           string JQueryVer = "1.7.1";
           System.Web.UI.ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new  ScriptResourceDefinition
           {
               Path = "~/Scripts/jquery-"  + JQueryVer + ".min.js",
               DebugPath = "~/Scripts/jquery-"  + JQueryVer + ".js",
               CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + JQueryVer + ".min.js",
               CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + JQueryVer + ".js",
               CdnSupportsSecureConnection = true,
               LoadSuccessExpression = "window.jQuery"
           });
       }

Now run this application if the user enter wrong information the error message will be shown as below:

 After this write the source code on file UserRegistration.cs on their is connection open and closed and their is first select query to check if this information already reside on your database or not if Yes than it show you as You Are Already Registered if No than their is a insert query to add you information on your database and registered yourself,their is also page.validate code to check if user enter complete and right information than connection open and execute the code.
The source code show you below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace WebApplication33
{
    public partial  class WebForm1 : System.Web.UI.Page
    {
        
        SqlConnection myConnection = new  SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString);
 
        protected void  Page_Load(object  sender, EventArgs e)
        {
 
        }
        protected void  registerBtn_Click1(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                myConnection.Open();
 
                string userInvalid = "You have already registered, please click to login.";
 
                string checkDatabase = "SELECT * FROM Users WHERE Email_Id = @em AND Password = @pas";
                SqlCommand command = new  SqlCommand(checkDatabase, myConnection);
                command.Parameters.AddWithValue("@em", email.Text);
                command.Parameters.AddWithValue("@pas", password.Text);
                command.ExecuteNonQuery();
                SqlDataReader reader = command.ExecuteReader();
 
                if (reader.HasRows)
                {
                    outputlabel.Text = userInvalid;
                    reader.Close();
                }
 
 
                 else
                {
                    try
                    {
                         
 
                        myConnection.Open();                 
                    }
                    catch (Exception ex)
                    {
                        myConnection.Close();
                        string query = "Insert into Users (FirstName,LastName,Gender,DateOfBirth,Email_Id,Password) Values (@fn,@ln,@gen,@dob,@em,@pas)";
                      
                        SqlCommand insertCommand = new  SqlCommand(query, myConnection);
                        
                        myConnection.Open();
                   
                            insertCommand.Parameters.AddWithValue("@fn", fname.Text);
                            insertCommand.Parameters.AddWithValue("@ln", lname.Text);
                            insertCommand.Parameters.AddWithValue("@gen", gender_dd.SelectedItem.Text);
                            insertCommand.Parameters.AddWithValue("@dob", date.Text);
                            insertCommand.Parameters.AddWithValue("@em", email.Text);
                            insertCommand.Parameters.AddWithValue("@pas", password.Text);
 
 
 
                            insertCommand.ExecuteNonQuery();
                         
                     
                         
                            myConnection.Close();
                            Response.Redirect("Login.aspx");
                        }
                     
 
                    finally { myConnection.Close(); }
                }
 
            }
        }
 
 
    }
}

Now run this application Your registration form will be created fill the information it will store on your Database.

now the UserRegistration Application has been created.
Now lets create a UserLogin form:
Now again right click on solution and select Add than New item and select Web Form name it  UserLogin.
UserLogin.aspx is used to create Html view and UserLogin.cs is used to write code behind on it,On Click operation.
Do same steps in UserLogin.aspx file select Toolbox and add TextBox submit button.
The source will be shown here:

<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <h2>LOGIN TO YOUR ACCOUNT</h2>
    <br />
    <br />
     <div>
 
            <table style="width: 100%">
                <tr>
                    <td style="width: 163px">UserName:</td>
                    <td>
                        <asp:TextBox ID="userbox" runat="server" CssClass="form-poshytip" placeholder="enter username"></asp:TextBox>
                        <br />
                        <br />
                    </td>
                </tr>
                <tr>
                    <td style="width: 163px">Password:</td>
                    <td>
                        <asp:TextBox ID="passwordbox" TextMode="Password" runat="server" CssClass="form-poshytip" placeholder="enter password"></asp:TextBox>
                        <br />
                        <br />
                    </td>
                </tr>
                <tr>
                    <td style="width: 163px"> </td>
                    <td>
                        <asp:Button OnClick="submitbtn_Click"    ID="submitbtn" runat="server" Text="Submit"  />
                         <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
                    </td>
                </tr>
            </table>
          </div>
 
    <br />
    <h6>Create An Account</h6>
    <br />
   <h3> <a href="registration.aspx">Click Here!</a></h3>
    </div>
    </form>
</body>
</html>

Now run this application you will see the UserLogin form on browser as:
Now write the code on its UserLogin.cs file in which there is select query to check if user already register or not if Not than redirect to the user on UserRegistration Form if user already registered than after add username and password it will login to the user.
The source code of UserLogin.cs file is shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace WebApplication33
{
    public partial  class WebForm1 : System.Web.UI.Page
    {
        
        SqlConnection myConnection = new  SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString);
 
        protected void  Page_Load(object  sender, EventArgs e)
        {
 
        }
        protected void  registerBtn_Click1(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                myConnection.Open();
 
                string userInvalid = "You have already registered, please click to login.";
 
                string checkDatabase = "SELECT * FROM Users WHERE Email_Id = @em AND Password = @pas";
                SqlCommand command = new  SqlCommand(checkDatabase, myConnection);
                command.Parameters.AddWithValue("@em", email.Text);
                command.Parameters.AddWithValue("@pas", password.Text);
                command.ExecuteNonQuery();
                SqlDataReader reader = command.ExecuteReader();
 
                if (reader.HasRows)
                {
                    outputlabel.Text = userInvalid;
                    reader.Close();
                }
 
 
                 else
                {
                    try
                    {
                         
 
                        myConnection.Open();                 
                    }
                    catch (Exception ex)
                    {
                        myConnection.Close();
                        string query = "Insert into Users (FirstName,LastName,Gender,DateOfBirth,Email_Id,Password) Values (@fn,@ln,@gen,@dob,@em,@pas)";
                      
                        SqlCommand insertCommand = new  SqlCommand(query, myConnection);
                        
                        myConnection.Open();
                   
                            insertCommand.Parameters.AddWithValue("@fn", fname.Text);
                            insertCommand.Parameters.AddWithValue("@ln", lname.Text);
                            insertCommand.Parameters.AddWithValue("@gen", gender_dd.SelectedItem.Text);
                            insertCommand.Parameters.AddWithValue("@dob", date.Text);
                            insertCommand.Parameters.AddWithValue("@em", email.Text);
                            insertCommand.Parameters.AddWithValue("@pas", password.Text);
 
 
 
                            insertCommand.ExecuteNonQuery();
                         
                     
                         
                            myConnection.Close();
                            Response.Redirect("WebForm2.aspx");
                        }
                     
 
                    finally { myConnection.Close(); }
                }
 
            }
        }
 
 
    }
}

Now the user registration form and login form has been created.