For this create a table Users in sql server database with ID,Uname,emlAddress columns
and add some records in it.
and add some records in it.
Add ScriptManager,Ajax UpdatePanel on the page, and inside ContentTemplate place two textbox, two image control to display images and two label controls for related messages.
Set AutoPostBack property of textbox to true.
HTML SOURCE OF PAGE
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
UserName:
<asp:TextBox ID="txtUName" runat="server"
ontextchanged="txtUName_TextChanged"
AutoPostBack="True"/>
<asp:Image ID="imgUsr" runat="server" Visible="false"/>
<asp:Label ID="lblUsr" runat="server"/>
Email ID:
<asp:TextBox ID="txtId" runat="server"
AutoPostBack="True"
ontextchanged="txtId_TextChanged"/>
<asp:Image ID="imgId" runat="server" Visible="false"/>
<asp:Label ID="lblId" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
Write below mentioned code in TextChanged Event of textbox
C# CODE
protected
void
txtUName_TextChanged(
object
sender, EventArgs e)
{
if
(txtUName.Text !=
string
.Empty)
{
string
strConnection = ConfigurationManager.ConnectionStrings
[
"ConnectionString"
].ConnectionString;
string
strSelect =
"SELECT COUNT(*) FROM Users WHERE
Uname = @Username"
;
SqlConnection con =
new
SqlConnection(strConnection);
SqlCommand cmd =
new
SqlCommand(strSelect,con);
SqlParameter user =
new
SqlParameter(
"@Username"
, SqlDbType.VarChar);
user.Value = txtUName.Text.Trim().ToString();
cmd.Parameters.Add(user);
con.Open();
int
result = (Int32)cmd.ExecuteScalar();
con.Close();
if
(result >= 1)
{
imgUsr.ImageUrl =
"unavailable.png"
;
imgUsr.Visible =
true
;
lblUsr.Text =
"Username not available"
;
lblUsr.ForeColor = System.Drawing.Color.Red;
}
else
{
imgUsr.ImageUrl =
"tick.png"
;
imgUsr.Visible =
true
;
lblUsr.Text =
"Available"
;
lblUsr.ForeColor = System.Drawing.Color.Green;
}
}
}
Similarly we can check email availability by writing following code
protected
void
txtId_TextChanged(
object
sender, EventArgs e)
{
if
(txtId.Text !=
string
.Empty)
{
string
strConnection = ConfigurationManager.ConnectionStrings
[
"ConnectionString"
].ConnectionString;
string
strSelect =
"SELECT COUNT(*) FROM Users WHERE emlAddress = @Email"
;
SqlConnection con =
new
SqlConnection(strConnection);
SqlCommand cmd =
new
SqlCommand(strSelect, con);
cmd.Parameters.AddWithValue(
"@Email"
, txtId.Text.Trim().ToString());
con.Open();
int
result = (Int32)cmd.ExecuteScalar();
con.Close();
if
(result >= 1)
{
imgId.ImageUrl =
"unavailable.png"
;
imgId.Visible =
true
;
lblId.Text =
"Email already registered"
;
lblId.ForeColor = System.Drawing.Color.Red;
}
else
{
imgId.ImageUrl =
"tick.png"
;
imgId.Visible =
true
;
lblId.Text =
"Available"
;
lblId.ForeColor = System.Drawing.Color.Green;
}
}
}
No comments:
Post a Comment