Thursday 13 December 2012

How to check user name using Ajax in Asp.Net.


In this article I will explain how to check user name availability using in Asp.Net.
Decription:-
User name check is required before you register first time  because it may be possible user name exist. It is widely used in website for registration . For this I have taken a textbox and one button in wenpage. When user type user name in textbox and when he leave the texbox it automatically check user name . For automatic check user name I have used Ajax  in Asp.Net.
Default.aspx:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
            <asp:TextBox ID="TextBox1" runat="server" AutoPostBack="true"
                ontextchanged="TextBox1_TextChanged" ></asp:TextBox><asp:Label ID="lblmessge" runat="server"
                    ></asp:Label>
        </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class CheckUserNameusingAjax : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
        if(TextBox1.Text!=string.Empty)
        {
            SqlConnection con = new SqlConnection(@"Data Source=SUSHIL-PC;Initial Catalog=modi;Integrated Security=True");
            SqlCommand com = new SqlCommand("select count(*) from user_registration where user_name=@user_name",con);
            SqlParameter sqlp = new SqlParameter("@user_name",SqlDbType.VarChar);
            sqlp.Value = TextBox1.Text.Trim().ToString();
            com.Parameters.Add(sqlp);
            con.Open();
            int res =Convert.ToInt32( com.ExecuteScalar());
            con.Close();
            if (res >= 1)
            {
                lblmessge.Text = "User Name not Available";
                lblmessge.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                lblmessge.Text = " Available";
                lblmessge.ForeColor = System.Drawing.Color.Green;
            }
        }
    }
}

Debug code and Run.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.