Friday 1 July 2011

Check username availability using ajax way in asp.net


Introduction: Hello friends, in this article i will explain that how we can check the username availabel or not using ajax way. Here i am checking the username available or not  using sql server 2005.

Implementation: create a new website add a page named Validate_User.aspx. Drag and drop the two textboxes,image control and a label from the toolbox named txtuser,txt_pwd , img_check_user and lbl_status  respectively. Here i am giving the complete code for the html page. Create a folder named images at the root directory. And place three images inside this folder after downloading. Below i am giving these three images.

Code for .aspx page:

<head runat="server">
    <title>Check Username Availability</title>
    <style type="text/css">
        .style1
        {
            width: 135px;
        }
    </style>
    <style type="text/css">
.waitingdiv {
background-color: #F5F8FA;
border: 1px solid #5A768E;
color: #333333;
font-size: 93%;
margin-bottom: 1em;
margin-top: 0.2em;
padding: 8px 12px;
width: 8.4em;
}
        .style2
        {
            width: 195px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
       <%-- here i am write a javascript code that will execuite for the waitingdiv --%>
        <script type="text/javascript">
            Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
            function BeginRequestHandler(sender, args) {
            var state = document.getElementById('loadingdiv').style.display;
            if (state == 'block') {
            document.getElementById('loadingdiv').style.display = 'none';
            } else {
            document.getElementById('loadingdiv').style.display = 'block';
            }
            args.get_postBackElement().disabled = true;
            }
            </script>
       
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
              
               <table style="width: 819px">
            <tr>
                <td class="style1">
                    User Name:</td>
                <td class="style2">
                    <asp:TextBox ID="TxtUser" runat="server"  AutoPostBack="true" Height="26px"
                        Width="160px" ontextchanged="TextBox1_TextChanged1"></asp:TextBox>
                    </td>
                    <td>
                    <%--inside the waitingdiv place image named "images/LoadingImage.gif" this
                    image will display only the time when code check the username available or not--%>
                    <div class="waitingdiv" id="loadingdiv" style="display:none; margin-left:5.3em">
       <img src="images/LoadingImage.gif" alt="Loading" />Please wait...
       </div>
      
     
      
    
       </td>
                    <td>
                    <div id="checkusername" runat="server"  Visible="false">
                    <asp:Image ID="img_chk_uname" runat="server" Width="17px" Height="17px"/>
                    <asp:Label ID="lblStatus" runat="server"></asp:Label>
                    </div>
</td>
            </tr>
            <tr>
                <td class="style1">
                    Password:</td>
                <td class="style2">
                    <asp:TextBox ID="txt_pwd" runat="server" Enabled="False" Height="26px"
                        Width="160px"></asp:TextBox>
                   </td>
            </tr>
        </table>
      
            </ContentTemplate>
        </asp:UpdatePanel>
   
    </div>
    </form>
</body>


Code for aspx.cs page:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class Validate_User : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection();
    protected void Page_Load(object sender, EventArgs e)
    {
        con.ConnectionString = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
        try
        {
            con.Open();
            //if (Session["adm"] == null)
            //{
            //    Response.Redirect("../login.aspx");

            //}
            if (Page.IsPostBack == false)
            {
             

              
            }

        }
        catch
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
        }


    }  

protected void  TextBox1_TextChanged1(object sender, EventArgs e)
 {
    // here i am checking username using sql server at the textchanged event of the textbox
       img_chk_uname.ImageUrl = "";

    if (!string.IsNullOrEmpty(TxtUser.Text))
        {

       // DataSet ds = BusinessLayer.GetvalidateUser(TxtUser.Text);
            // here i am using SqlDataAdapter for thw query execution.
        SqlDataAdapter adp = new SqlDataAdapter("select * from tbemp  where ename=@ename", con);
        // here am passing parameter named ename that will be passed fron the enterd text in the textbox
        adp.SelectCommand.Parameters.Add("@ename", SqlDbType.VarChar,50).Value = TxtUser.Text;
        DataSet ds = new DataSet();
        //here m filling dataset ds with the SqlDataAdapter
        adp.Fill(ds);
        // here i am checking the value inside the ds. if any value will come in the ds then execute the if condition
        // and it gives us a message that "UserName Already Exit" in a label
        if (ds.Tables[0].Rows.Count > 0)
        {
            img_chk_uname.ImageUrl = "";
            checkusername.Visible = true;
            // if this condition will be satisfyied then "images/NotAvailable.jpg" image will display
            img_chk_uname.ImageUrl = "images/NotAvailable.jpg";
            lblStatus.Text = "UserName Already Exit";
            System.Threading.Thread.Sleep(4000);
            txt_pwd.Enabled = false;
        }
        else
        {
            // here i am checking the value inside the ds. if no any value will come in the ds then execute the else condition
            // and it gives us a message that "UserName Available" in a label
            img_chk_uname.ImageUrl = "";
            checkusername.Visible = true;
            // if this condition will be satisfyied then "images/Icon_Available.gif" image will display
            img_chk_uname.ImageUrl = "images/Icon_Available.gif";
            lblStatus.Text = "UserName Available";
            System.Threading.Thread.Sleep(4000);
            txt_pwd.Enabled = true;
         }
        }
        else
        {
            checkusername.Visible = false;
        }
  }

}

See output in this image:




Sql Script for database:

/****** Object:  Table [dbo].[tbemp]    Script Date: 07/01/2011 12:24:47 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tbemp]') AND type in (N'U'))
DROP TABLE [dbo].[tbemp]
GO
/****** Object:  Table [dbo].[tbemp]    Script Date: 07/01/2011 12:24:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tbemp]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[tbemp](
      [id] [int] IDENTITY(1,1) NOT NULL,
      [ename] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [eadd] [varchar](500) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [email] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [uname] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [pwd] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
 CONSTRAINT [PK_tbemp] PRIMARY KEY CLUSTERED
(
      [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON)
)
END
GO
SET IDENTITY_INSERT [dbo].[tbemp] ON
INSERT [dbo].[tbemp] ([id], [ename], [eadd], [email], [uname], [pwd]) VALUES (3, N'priyanka', N'#weg', N'priyanka_66@gmail.com', N'pri', N'pri')
INSERT [dbo].[tbemp] ([id], [ename], [eadd], [email], [uname], [pwd]) VALUES (19, N'Bharat', N'@kdsj', N'bharti222000@yahoo.com', N'harpreet', N'1234')
INSERT [dbo].[tbemp] ([id], [ename], [eadd], [email], [uname], [pwd]) VALUES (21, N'hareesh', N'#764237', N'bharti222000@yahoo.com', N'hareesh', N'12345')
INSERT [dbo].[tbemp] ([id], [ename], [eadd], [email], [uname], [pwd]) VALUES (28, N'vikram', N'#455', N'`vikram@gmail.com', N'vikram', N'vikram')
SET IDENTITY_INSERT [dbo].[tbemp] OFF

Conclusion
Through this article, you have learned how to check username available or not in web site using asp.net






No comments:

Post a Comment