Hi power,
Here i have created complete sample. Refer the below code.
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
window.onload = function Test() {
PageMethods.CheckUserName(document.getElementById("<%=txtUsername.ClientID%>").value, Username_OnSuccess);
}
function UsernameAvailability() {
PageMethods.CheckUserName(document.getElementById("<%=txtUsername.ClientID%>").value, Username_OnSuccess);
}
function Username_OnSuccess(response) {
var mesg = document.getElementById("Username_Check");
if (document.getElementById("<%=txtUsername.ClientID%>").value.length > 0) {
switch (response) {
case "true":
mesg.style.color = "green";
mesg.innerHTML = "Available";
break;
case "false":
mesg.style.color = "red";
mesg.innerHTML = "Username already taken.";
break;
}
}
else {
mesg.innerHTML = "";
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:TextBox ID="txtUsername" onChange="UsernameAvailability()" onkeyup="UsernameAvailability()"
ondrop="return false;" onpaste="return false;" runat="server" Text="maria" />
<span id="Username_Check"></span>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
C#
[System.Web.Services.WebMethod()]
public static string CheckUserName(string userName)
{
string returnValue = string.Empty;
try
{
string consString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection conn = new SqlConnection(consString);
SqlCommand cmd = new SqlCommand("CheckUsername", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Name", userName.Trim());
conn.Open();
returnValue = cmd.ExecuteScalar().ToString();
conn.Close();
}
catch (Exception ex)
{
returnValue = "error";
}
return returnValue;
}
VB.Net
<System.Web.Services.WebMethod()> _
Public Shared Function CheckUserName(ByVal userName As String) As String
Dim returnValue As String = String.Empty
Try
Dim consString As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
Dim conn As New SqlConnection(consString)
Dim cmd As New SqlCommand("CheckUsername", conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Name", userName.Trim())
conn.Open()
returnValue = cmd.ExecuteScalar().ToString()
conn.Close()
Catch
returnValue = "error"
End Try
Return returnValue
End Function
Screenshot