Registration Form With Captcha Image in C#

Introduction

In this article I will explain how to create a registration form in ASP.NET C#. This article also explains how we to use Stored Procedures instead of explicit SQL statements to add data from a form to a database.

registration form

Use the following procedure to create a sample.

Step 1: Create a database and add a table for storing the data as in the following:

table

Step 2: Create a Stored Procedure to store the records in the database as in the following:

Create PROCEDURE [dbo].[sp_EmpInformation]

@UserName varchar(50),

@Password varchar(50),

@FirstName varchar(50),

@LastName varchar(50),

@Email varchar(50),

@PhoneNo varchar(50),

@Location varchar(50),

@Created_By varchar(50),

@ERROR VARCHAR(100) OUT

 

AS

 

BEGIN-- SET NOCOUNT ON added to prevent extra result sets from-- interfering with SELECT statements.               

SET NOCOUNT ON;

 

---Checking Condition if User exists or not if user not exists returns different message if exists returns different message

 

IF NOT EXISTS(SELECT * FROM Employee_Information WHERE UserName=@UserName)

BEGIN INSERT INTO Employee_Information

(

    UserName,

    [Password],

    FirstName,

    LastName,

    Email,

    PhoneNo,

    Location,

    Created_By

)VALUES(@UserName,

@Password,

@FirstName,

@LastName,

@Email,

@PhoneNo,

@Location,

@Created_By

)

SET @ERROR=@UserName+' has registered successfully.'

END

ELSE

  BEGIN

      SET @ERROR=@UserName + ' has already exists.'

  END

End

Step 3: Open Visual Studio and select create Web application.

Step 4: Add a new Web page Emp_Registration.aspx and design it as below:

<div>

        <asp:ScriptManager ID="SM1" runat="server">

        </asp:ScriptManager>

        <table align="center">

            <tr>

                <td align="center" colspan="2">

                    <h2>

                        Registration Form</h2>

                </td>

            </tr>

            <tr>

                <td>

                    <asp:Label ID="lbluser" runat="server" Text="Username"></asp:Label>

                </td>

                <td>

                    <asp:TextBox ID="txtuser" runat="server"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td>

                    <asp:Label ID="lblpwd" runat="server" Text="Password"></asp:Label>

                </td>

                <td>

                    <asp:TextBox ID="txtpwd" runat="server" TextMode="Password"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td>

                    <asp:Label ID="lblcnfmpwd" runat="server" Text="Confirm Password"></asp:Label>

                </td>

                <td>

                    <asp:TextBox ID="txtcnmpwd" runat="server" TextMode="Password"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td>

                    <asp:Label ID="lblfname" runat="server" Text="FirstName"></asp:Label>

                </td>

                <td>

                    <asp:TextBox ID="txtfname" runat="server"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td>

                    <asp:Label ID="lbllname" runat="server" Text="LastName"></asp:Label>

                </td>

                <td>

                    <asp:TextBox ID="txtlname" runat="server"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td>

                    <asp:Label ID="lblemail" runat="server" Text="Email"></asp:Label>

                </td>

                <td>

                    <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td>

                    <asp:Label ID="lblCnt" runat="server" Text="Phone No"></asp:Label>

                </td>

                <td>

                    <asp:TextBox ID="txtphone" runat="server"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td>

                    <asp:Label ID="lbladd" runat="server" Text="Location"></asp:Label>

                </td>

                <td align="left">

                    <asp:TextBox ID="txtlocation" runat="server"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td>

                </td>

                <td valign="middle">

                    <asp:UpdatePanel ID="UP1" runat="server">

                        <ContentTemplate>

                            <table>

                                <tr>

                                    <td style="height: 50px; width: 100px;">

                                        <asp:Image ID="imgCaptcha" runat="server" />

                                    </td>

                                    <td valign="middle">

                                        <asp:Button ID="btnRefresh" runat="server" Text="Refresh" OnClick="btnRefresh_Click" />

                                    </td>

                                </tr>

                            </table>

                        </ContentTemplate>

                    </asp:UpdatePanel>

                </td>

            </tr>

            <tr>

                <td>

                    Enter above captcha code :

                </td>

                <td>

                    <asp:TextBox ID="txtCaptcha" runat="server" Width="200px"></asp:TextBox>

                </td>

            </tr>

            <tr>

                <td align="left" colspan="2">

                    <asp:Button ID="btnsubmit" runat="server" Text="Save" OnClick="btnsubmit_Click" />

                    &nbsp;&nbsp;<asp:Button ID="btnReset" Text="Reset" runat="server" />

                </td>

            </tr>

            <tr>

                <td colspan="2">

                    <span style="color: Red; font-weight: bold">

                        <asp:Label ID="lblErrorMsg" runat="server"></asp:Label></span>

                </td>

            </tr>

        </table>

    </div>

Step 5: Go to the Emp_Registration.aspx.cs page and add code.

Step 6 : Add code for the Page Load as below:

protected void Page_Load(object sender, EventArgs e)

{

    FillCapctha();

}

 

void FillCapctha()

{

    try

    {

        Random random = new Random();

         string combination = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

         StringBuilder captcha = new StringBuilder();

         for (int i = 0; i < 6; i++)
         {

            captcha.Append(combination[random.Next(combination.Length)]);

            Session["captcha"] = captcha.ToString();

            imgCaptcha.ImageUrl = "GenerateCaptcha.aspx?" + DateTime.Now.Ticks.ToString();

        }

        catch

        {

               throw;

        }
 }

Step 7: Add code for the button Submit click as in the following:

protected void btnsubmit_Click(object sender, EventArgs e)

{

    if (Session["captcha"].ToString() != txtCaptcha.Text)

        lblErrorMsg.Text = "Invalid Captcha Code";

     else

     {

         if (txtpwd.Text == txtcnmpwd.Text)

         {

               string UserName = txtuser.Text;

               string Password = txtpwd.Text;

               string ConfirmPassword = txtcnmpwd.Text;

               string FirstName = txtfname.Text;

               string LastName = txtlname.Text;

               string Email = txtEmail.Text;

               string Phoneno = txtphone.Text;

               string Location = txtlocation.Text;

               string Created_By = txtuser.Text;

               SqlConnection con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=LMS;Integrated Security=True");

               con.Open();

               SqlCommand cmd = new SqlCommand("sp_EmpInformation", con);

               cmd.CommandType = CommandType.StoredProcedure;

               cmd.Parameters.AddWithValue("@UserName", UserName);

               cmd.Parameters.AddWithValue("@Password", Password);

               cmd.Parameters.AddWithValue("@FirstName", FirstName);

                cmd.Parameters.AddWithValue("@LastName", LastName);

                cmd.Parameters.AddWithValue("@Email", Email);

                cmd.Parameters.AddWithValue("@PhoneNo", Phoneno);

                 cmd.Parameters.AddWithValue("@Location", Location);

                 cmd.Parameters.AddWithValue("@Created_By", Created_By);

                 cmd.Parameters.Add("@ERROR", SqlDbType.Char, 500);

                 cmd.Parameters["@ERROR"].Direction = ParameterDirection.Output;

                 cmd.ExecuteNonQuery();

                 if (!string.IsNullOrEmpty(cmd.Parameters["@ERROR"].Value.ToString()))

                 {

                     message = (string)cmd.Parameters["@ERROR"].Value;

                 }

                 con.Close();

            }

            else

            {

                Page.RegisterStartupScript("UserMsg", "<Script language='javascript'>alert('" + "Password mismatch" + "');</script>");

            }

            lblErrorMsg.Text = message;

            ClearControls();

      }                    

}

Step 8: Add code for the Refresh button as in the following:

protected void btnRefresh_Click(object sender, EventArgs e)

{

    FillCapctha();

}

Step 9: Add another Webform GenerateCaptcha.aspx

Step 10: Add the following code on the page Load of GenerateCaptcha.aspx:

Response.Clear();

int height = 30;

int width = 100;

Bitmap bmp = new Bitmap(width, height);

RectangleF rectf = new RectangleF(10, 5, 0, 0);

Graphics g = Graphics.FromImage(bmp);

g.Clear(Color.White);

g.SmoothingMode = SmoothingMode.AntiAlias;

g.InterpolationMode = InterpolationMode.HighQualityBicubic;

g.PixelOffsetMode = PixelOffsetMode.HighQuality;

g.DrawString(Session["captcha"].ToString(), new Font("Thaoma", 12, FontStyle.Italic), Brushes.Chocolate, rectf);

g.DrawRectangle(new Pen(Color.Blue), 1, 1, width - 2, height - 2);

g.Flush();

Response.ContentType = "image/jpeg";

bmp.Save(Response.OutputStream, ImageFormat.Jpeg);

g.Dispose();

bmp.Dispose();

Step 11: Press F5 to run the application.

Step 12: Add a new entry in the registration form as in the following:

Entry in registration form

Step 13: Records are stored in the database as below:
 
Records stored in the database

Conclusion

In this article I have explained how to work with a registration form with Captcha feature and store data in SQL Server using Stored Procedure.