Tuesday, 21 February 2012

Login form in asp.net



Login Form Using Sql Server in asp.net
Form Design

Source Code:
 Paste This Source to your form source page.
<body> 
<form id="form1" runat="server">
<div>
 <asp:Login ID="Login1" runat="server" Height="201px" 
 OnAuthenticate="Login1_Authenticate"
 Width="344px" EnableTheming="True">
 
 </asp:Login>
</div>
</form>
</body> 
Code Behind C#: 
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
            ViewState["LoginErrors"] = 0;
    }
    protected void Login1_Authenticate(object sender,
     AuthenticateEventArgs e)
    {
        if (YourValidationFunction(Login1.UserName, Login1.Password))
        {
           // e.Authenticated = true;
            Login1.Visible =true;
            Session["t1"] = Login1.UserName;
            Response.Redirect("Default2.aspx");
        }
        else
        {
            e.Authenticated = false;
        }
    }  
 protected void Login1_LoginError(object sender, EventArgs e)
    {
        if (ViewState["LoginErrors"] == null)
            ViewState["LoginErrors"] = 0;
 
        int ErrorCount = (int)ViewState["LoginErrors"] + 1;
        ViewState["LoginErrors"] = ErrorCount;
 
   if ((ErrorCount > 3) && (Login1.PasswordRecoveryUrl != string.Empty))
            Response.Redirect(Login1.PasswordRecoveryUrl);
    }
  private bool YourValidationFunction(string UserName, string Password)
    {
        bool boolReturnValue = false;       
    string strConnection = "server=.;database=login;uid=sa;pwd=root;";
        SqlConnection sqlConnection = new SqlConnection(strConnection);
        String SQLQuery = "SELECT uname, pwds FROM log1";
        SqlCommand command = new SqlCommand(SQLQuery, sqlConnection);
        SqlDataReader Dr;
        sqlConnection.Open();
        Dr = command.ExecuteReader();
        while (Dr.Read())
        {
if ((UserName == Dr["uname"].ToString()) & 
(Password == Dr["pwds"].ToString()))
          {
                boolReturnValue = true;
            }
            Dr.Close();
            return boolReturnValue;
        }
        return boolReturnValue;
    }}
Database:
Database Name: login
Table Name:log1