Sie sind auf Seite 1von 8

Home

Categories

Forums

Contact

Simple User Registration Form Example in


ASP.Net
03 Jan 2014 Mudassar Khan 28 Comments 512013 Views
ASP.Net

Here Mudassar Ahmed Khan has explained how to build a


simple user registration form that will allow user register
to the website in ASP.Net using C# and VB.Net.

User will fill up the registration form with details such as


username, password, email address, etc. and these details
will be saved in the database table.

The registration form will also make sure that duplicate


username and email addresses are not saved by verifying
whether username and email address must not exists in
the table.
Download FREE APIs to work with ALL kinds of office files - http://e-iceblue.com/free-api
In this article I will explain how to build a simple user registration form that will allow user register to
the website in ASP.Net using C# and VB.Net.
User will fill up the registration form with details such as username, password, email address, etc. and
these details will be saved in the database table.
The registration form will also make sure that duplicate username and email addresses are not saved
by verifying whether username and email address must not exists in the table.

Database
For this article I have created a new database named LoginDB which contains the following table
named Users in it.

In the above table column UserId is set as primary key and it Identity property is set to true.
Note: The SQL for creating the database is provided in the attached sample code.

HTML Markup
The HTML Markup consists of some TextBox, their corresponding Validators and a Button. Other than
RequiredField Validators theres a CompareValidator to compare passwords and a
RegularExpressionValidator to validate email address.
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<th colspan="3">
Registration
</th>
</tr>
<tr>
<td>
Username
</td>
<td>
<asp:TextBox ID="txtUsername" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="Red"
ControlToValidate="txtUsername"
runat="server" />
</td>
</tr>
<tr>
<td>
Password
</td>
<td>
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password" />
</td>
<td>
<asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="Red"
ControlToValidate="txtPassword"
runat="server" />
</td>
</tr>
<tr>
<td>
Confirm Password
</td>
<td>
<asp:TextBox ID="txtConfirmPassword" runat="server"
TextMode="Password" />
</td>
<td>
<asp:CompareValidator ErrorMessage="Passwords do not match."
ForeColor="Red" ControlToCompare="txtPassword"
ControlToValidate="txtConfirmPassword" runat="server" />
</td>
</tr>
<tr>
<td>
Email
</td>
<td>
<asp:TextBox ID="txtEmail" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ErrorMessage="Required"
Display="Dynamic" ForeColor="Red"
ControlToValidate="txtEmail" runat="server" />
<asp:RegularExpressionValidator runat="server" Display="Dynamic"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
ControlToValidate="txtEmail" ForeColor="Red"
ErrorMessage="Invalid email address." />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button Text="Submit" runat="server" OnClick="RegisterUser" />
</td>
<td>
</td>
</tr>
</table>

Stored Procedure to insert the User details


The following stored procedure is used to insert the user details such as username, password and
email address.
The stored procedure first checks whether the username supplied already exists, if yes then it will
return negative 1 value.
Then the stored procedure checks whether the email address supplied already exists, if yes then it will
return negative 2 value.
If both username and email address are valid then the record will be inserted and the auto-generated
UserId will be returned by the stored procedure.
CREATE PROCEDURE [dbo].[Insert_User]
@Username NVARCHAR(20),
@Password NVARCHAR(20),
@Email NVARCHAR(30)
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS(SELECT UserId FROM Users WHERE Username = @Username)
BEGIN
SELECT -1 -- Username exists.
END
ELSE IF EXISTS(SELECT UserId FROM Users WHERE Email = @Email)
BEGIN
SELECT -2 -- Email exists.
END
ELSE
BEGIN
INSERT INTO [Users]
([Username]
,[Password]
,[Email]
,[CreatedDate])
VALUES
(@Username
,@Password
,@Email
,GETDATE())

SELECT SCOPE_IDENTITY() -- UserId


END
END

Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient

Inserting the User Details


The following event handler is raised when the submit button is clicked, here the values from the
Registration Forms TextBoxes are passed to the stored procedure and the stored procedure is
executed.
The return value from the stored procedure is captured in a variable and then based on its value
appropriate message is displayed using JavaScript Alert message box.
C#
protected void RegisterUser(object sender, EventArgs e)
{
int userId = 0;
string constr =
ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Insert_User"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username",
txtUsername.Text.Trim());
cmd.Parameters.AddWithValue("@Password",
txtPassword.Text.Trim());
cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
cmd.Connection = con;
con.Open();
userId = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
}
string message = string.Empty;
switch (userId)
{
case -1:
message = "Username already exists.\\nPlease choose a different
username.";
break;
case -2:
message = "Supplied email address has already been used.";
break;
default:
message = "Registration successful.\\nUser Id: " +
userId.ToString();
break;
}
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" +
message + "');", true);
}
}

VB.Net
Protected Sub RegisterUser(sender As Object, e As EventArgs)
Dim userId As Integer = 0
Dim constr As String =
ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("Insert_User")
Using sda As New SqlDataAdapter()
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Username",
txtUsername.Text.Trim())
cmd.Parameters.AddWithValue("@Password",
txtPassword.Text.Trim())
cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim())
cmd.Connection = con
con.Open()
userId = Convert.ToInt32(cmd.ExecuteScalar())
con.Close()
End Using
End Using
Dim message As String = String.Empty
Select Case userId
Case -1
message = "Username already exists.\nPlease choose a different
username."
Exit Select
Case -2
message = "Supplied email address has already been used."
Exit Select
Case Else
message = "Registration successful.\nUser Id: " +
userId.ToString()
Exit Select
End Select
ClientScript.RegisterStartupScript([GetType](), "alert",
(Convert.ToString("alert('") & message) + "');", True)
End Using
End Sub

Message Box when registration is successful

Message Box when username already exists

Message Box when email address already exists

User record inserted in table

Downloads

Related Articles
Send user Confirmation email after Registration with Activation Link in ASP.Net
Here Mudassar Ahmed Khan has explained how to send user confirmation email after
registration with Activation link in ASP.Net using C# and VB.Net. In order to validate the
email address of the user provided during registration, a confirmation email with activation
link in sent to the email address and when user clicks the link, his email address is verified
and his account gets activated.
Comments

ThanksApr 12, 2014 11:04 AM 58.97.142.88


This is really effective

Reo NakataApr 27, 2014 08:04 PM 114.79.29.247

Thanks Works for Me

Jeevanathan UMay 21, 2014 11:05 AM 27.251.114.3

Very nice and informative yaar. thanks

shaparakJun 04, 2014 01:06 PM 176.12.66.21

thank u sir.
wish u best of luck

HugoJul 08, 2014 07:07 PM 189.224.51.61

thank u sir great job.

Add Comments
You can add your comment about this article using the form below. Make sure you provide a
valid email address
else you won't be notified when the author replies to your comment
Please note that all comments are moderated and will be deleted if they are

Not relavant to the article


Spam

Advertising campaigns or links to other sites

Abusive content.

Please do not post code, scripts or snippets.


Name

Email

Comment

Security code:

What our readers say


Mayank Pathak
Awesome Mudassar ...
I am already a follower of your posts on forums.asp.net....
Nice example mate...It works superb.
Subscribe
Please enter your email address:

2016 www.aspsnippets.com All rights reserved | Privacy Policy | Powered by Excelasoft

Solutions

Das könnte Ihnen auch gefallen