TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
How to create Captcha in ASP.Net with C#
Neethu Eapen
Oct 21
2014
Code
1.5
k
0
1
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
In aspx page
<
form
id
=
"form1"
runat
=
"server"
>
<
div
>
<
div
>
<
h1
align
=
"center"
>
captcha image
</
h1
>
<
table
align
=
"center"
>
<
tr
>
<
td
>
Prove You are not a robot:
</
td
>
<
td
>
<
asp:TextBox
ID
=
"TextBox1"
runat
=
"server"
>
</
asp:TextBox
>
</
td
>
<
td
>
<
asp:TextBox
ID
=
"txtrobocomp"
runat
=
"server"
Font-Names
=
"Vivaldi"
Font-Size
=
"X-Large"
Font-Bold
=
"True"
BackColor
=
"#CC99FF"
ForeColor
=
"#CC0066"
Width
=
"148px"
Height
=
"33px"
>
</
asp:TextBox
>
</
td
>
<
td
>
<
asp:ImageButton
ID
=
"ImageButton1"
runat
=
"server"
ImageUrl
=
""
Width
=
"30px"
Height
=
"30px"
AlternateText
=
"refresh"
onclick
=
"ImageButton1_Click"
/>
</
td
>
<
%--
<
td
>
<
asp:ImageButton
ID
=
"ImageButton2"
runat
=
"server"
ImageUrl
=
"~/images/download.jpg"
Height
=
"30px"
Width
=
"30px"
onclick
=
"ImageButton2_Click"
/>
</
td
>
<
td
>
--%
>
<
asp:CompareValidator
ID
=
"CompareValidator1"
runat
=
"server"
ControlToValidate
=
"TextBox1"
ControlToCompare
=
"txtrobocomp"
ErrorMessage
=
"Please enter correct Text"
ForeColor
=
"Red"
>
</
asp:CompareValidator
>
</
td
>
</
tr
>
<
tr
>
<
td
colspan
=
"6"
align
=
"center"
>
<
asp:Button
ID
=
"Button1"
runat
=
"server"
Text
=
"Submit"
style
=
"height: 26px"
/>
</
td
>
</
tr
>
</
table
>
</
div
>
</
form
>
in aspx.cs page
protected
void
Page_Load(
object
sender, EventArgs e)
{
if
(!IsPostBack)
{
StringBuilder builder =
new
StringBuilder();
builder.Append(RandomNumber(10, 99));
builder.Append(RandomString(3,
true
));
builder.Append(RandomString(2,
false
));
txtrobocomp.Text = builder.ToString();
}
}
protected
void
ImageButton1_Click(
object
sender, ImageClickEventArgs e)
{
StringBuilder builder =
new
StringBuilder();
builder.Append(RandomNumber(10, 99));
builder.Append(RandomString(3,
true
));
builder.Append(RandomString(2,
false
));
txtrobocomp.Text = builder.ToString();
}
private
int
RandomNumber(
int
min,
int
max)
{
Random rd =
new
Random();
return
rd.Next(min, max);
}
private
string
RandomString(
int
size,
bool
lowerCase)
{
StringBuilder builder =
new
StringBuilder();
Random rd =
new
Random();
char
ch;
for
(
int
i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * rd.NextDouble() + 65)));
builder.Append(ch);
}
if
(lowerCase)
return
builder.ToString().ToLower();
return
builder.ToString();
}
}
captcha