Thursday, July 25, 2013

How to Create Login Form in Asp.net OR Login Form with Check Username and Password aviabilty in Asp.net

Introduction: In this post I will explain how we can create Login form with check Username and Password aviability  in Asp.net.
Login Form

Description:
In the last article i have explained How to Create registration form in Asp.net.

After the successfully registration to website, user redirect to login page/form of website. Users enter their username and pasword information to enter in website. If username and password is exis than they will be redirect to welcome page of website otherwise got a message for registration or Invalid user/Password.
To show user login form  Example I created a Table USER_REGISTRATION:
ID
int
USERNAME
varchar(50)
PASSWORD
varchar(50)
FIRST_NAME
varchar(50)
LAST_NAME
varchar(50)
SEX
varchar(50)
EMAIL_ID
varchar(50)

Here ID is autoincrement and primary key.
Take a new website. Add a webform to website. Drag and drop the controls from Toolbox and Design the  .aspx page as shown below:
  <table align="center">
    <tr><td>Username:-</td><td>
        <asp:TextBox ID="txtusername" runat="server"></asp:TextBox></td></tr>
        <tr><td>&nbsp;</td></tr>
        <tr><td>Password:-</td><td>
            <asp:TextBox ID="txtpassword" TextMode="Password" runat="server"></asp:TextBox></td></tr>
            <tr><td>&nbsp;</td><td>
                <asp:Button ID="btnlogin" runat="server" Text="Login"
                    onclick="btnlogin_Click" /></td></tr>
                    <tr><td>Forget Password?</td><td>
                        <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">Click Here</asp:LinkButton></td></tr>
                </table>

NOTE: Do not forget to add ConnectionString in web.config file of projec/website:
<connectionStrings>
      <add name="Connection" connectionString="Data Source=VIJAY-PC;Initial Catalog=TEST_APPLICATION;Integrated Security=True"/>

    </connectionStrings>

After that on button click write the below given code (.aspx.cs):
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());
  protected void btnlogin_Click(object sender, EventArgs e)
    {
               try
        {
            if(checknullvalidation() == false)
            {
                return;
            }
                  
            string query = "Select * from USER_REGISTRATION where USERNAME = @USERNAME and PASSWORD = @PASSWORD";
            SqlCommand cmd = new SqlCommand(query,con);
            con.Open();
            cmd.Parameters.AddWithValue("@USERNAME", txtusername.Text.Trim());
            cmd.Parameters.AddWithValue("@PASSWORD", txtpassword.Text);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adp.Fill(dt);         
            if (dt.Rows.Count > 0)
            {
                //session for user
                Session["USERNAME"] = txtusername.Text;
                Response.Redirect("Welcome.aspx");
                con.Close();
            }
            else
            {               
                ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Username/Password Doesn,t Match')</script>");
            }
        }
        catch(Exception ex)
        {
        }
    }
//Check Validation
    public bool checknullvalidation()
    {
        if (txtusername.Text.Trim() == string.Empty)
        {
            Messagebox("Please enter username");
            txtusername.Focus();
            return false;
        }
        if (txtpassword.Text.Trim() == string.Empty)
        {
            Messagebox("Please enter your password");
            txtpassword.Focus();
            return false;
        }
        return true;
    }
//Show Message
    private void Messagebox(string Message)
    {
        Label lblMessageBox = new Label();

        lblMessageBox.Text =
            "<script language='javascript'>" + Environment.NewLine +
            "window.alert('" + Message + "')</script>";
        Page.Controls.Add(lblMessageBox);
    }

Check Session on Welcome.aspx.cs page Load:

protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["USERNAME"] != null)
        {
            lblusername.Text = Session["USERNAME"].ToString();
        }
    }

In VB (.aspx.vb)

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

Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("Connection").ToString())

    Protected Sub btnlogin_Click(sender As Object, e As System.EventArgs) Handles btnlogin.Click
               Try
            If checknullvalidation() = False Then
                Return
            End If
            Dim query As String = "Select * from USER_REGISTRATION where USERNAME = @USERNAME and PASSWORD = @PASSWORD"
            Dim cmd As New SqlCommand(query, con)
            con.Open()
            cmd.Parameters.AddWithValue("@USERNAME", txtusername.Text.Trim())
            cmd.Parameters.AddWithValue("@PASSWORD", txtpassword.Text)
            Dim adp As New SqlDataAdapter(cmd)
            Dim dt As New DataTable()
            adp.Fill(dt)
            If dt.Rows.Count > 0 Then
               'session for user
                Session("USERNAME") = txtusername.Text
                Response.Redirect("Welcome.aspx")
                con.Close()
            Else
                ClientScript.RegisterStartupScript(Page.[GetType](), "validation", "<script language='javascript'>alert('Username/Password Doesn,t Match')</script>")
            End If
        Catch ex As Exception
        End Try
    End Sub
    'Check Validation
    Public Function checknullvalidation() As Boolean
        If txtusername.Text.Trim() = String.Empty Then
            Messagebox("Please enter username")
            txtusername.Focus()
            Return False
        End If
        If txtpassword.Text.Trim() = String.Empty Then
            Messagebox("Please enter your password")
            txtpassword.Focus()
            Return False
        End If
        Return True
    End Function
    'Show Message
    Private Sub Messagebox(Message As String)
        Dim lblMessageBox As New Label()
        lblMessageBox.Text = "<script language='javascript'>" + Environment.NewLine & "window.alert('" & Message & "')</script>"
        Page.Controls.Add(lblMessageBox)
    End Sub

Check Session on Welcome.aspx.vb page Load:

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Session("USERNAME") IsNot Nothing Then
            lblusername.Text = Session("USERNAME").ToString()
        End If
    End Sub

Now run the project and check the result.

No comments:

Post a Comment