Check Username Availability Using Ajax In Asp.Net
In this post we will learn how to Check Username Availability Using Ajax In Asp.Net.Here we are using Asp.Net Ajax functionality to accomplish this.On TextChanged event of textbox we are checking in Database for the same username existence.
Design:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Check Username Availability Using Ajax In Asp.Net</title> <style type="text/css"> body { width:980px; margin:0px auto; font-family:Calibri; text-align:center; } h1 { text-align:center; margin-bottom:100px; } </style> </head> <body> <form id="form1" runat="server"> <div> <h1>Check Username Availability Using Ajax In Asp.Net</h1> <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> UserName: <asp:TextBox ID="fusr" AutoPostBack="true" OnTextChanged="fusr_TextChanged" runat="server"></asp:TextBox> <asp:Image ID="uavb" runat="server" Visible="false" /> <asp:Label ID="ulbl" runat="server"></asp:Label> </ContentTemplate> </asp:UpdatePanel> </div> </form> </body> </html>
Code:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void fusr_TextChanged(object sender, EventArgs e) { if (fusr.Text != string.Empty) { SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=dev;User ID=sa;Password=hightech"); con.Open(); string strSelect = "SELECT COUNT(*) FROM Users WHERE username = @Username"; SqlCommand cmd = new SqlCommand(strSelect, con); SqlParameter user = new SqlParameter("@Username", SqlDbType.VarChar); user.Value = fusr.Text.Trim().ToString(); cmd.Parameters.Add(user); int result = (Int32)cmd.ExecuteScalar(); con.Close(); if (result >= 1) { uavb.ImageUrl = "notok.png"; uavb.Visible = true; ulbl.Text = "Username not available"; ulbl.ForeColor = System.Drawing.Color.Red; } else { uavb.ImageUrl = "ok.png"; uavb.Visible = true; ulbl.Text = "Available"; ulbl.ForeColor = System.Drawing.Color.Green; } } } }