Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

This tutorial will demonstrate how to create a registration page for new users to your site.

This
registration page will utilize the same principles used in the Login Page Tutorial, so this should be no
more difficult to do than the login page. I am using the SQL Server 2000, and programmed this part
of the application in Visual Studio .NET 2003. I choose VB because it is more natural language to
me, but there is no reason you can't use the same concepts I use here to code this in any other
language in the .NET framework.

1. Create the basic HTML layout for the registration page. REGISTER.ASPX
- This page will require all entries to be filled in for a successful registration
- UserName, Password, FirstName and LastName
(Toggle Plain Text)

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="Register.aspx.vb"


Inherits="NorthLogin3.Register"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Register</title>
<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<body ms_positioning="GridLayout">
<h1>Welcome to the Norwthwind DB Registration Page</h1>
<form id="frmRegister" method="post" runat="server">
<table id="tblRegister" border="1" cellpadding="2"
cellspacing="1">
<tr>
<td style="WIDTH: 108px">User Name:</td>
<td><asp:textbox id="txtUserName"
runat="server"></asp:textbox><font color="#ff3300"
size="4"><strong>*</strong></font></td>
<td><asp:requiredfieldvalidator id="rvUserName"
runat="server" errormessage="<-- Required"
controltovalidate="txtUserName"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td style="WIDTH: 108px; HEIGHT:
23px">Password:</td>
<td style="HEIGHT: 23px"><asp:textbox
id="txtPassword" runat="server" textmode="Password"></asp:textbox><font
color="#ff3300" size="4"><strong>*</strong></font></td>
<td><asp:requiredfieldvalidator id="rvPassword"
runat="server" errormessage="<-- Required"
controltovalidate="txtPassword"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td style="WIDTH: 108px">First Name:</td>
<td><asp:textbox id="txtFirst"
runat="server"></asp:textbox><font color="#ff3300"
size="4"><strong>*</strong></font></td>
<td><asp:requiredfieldvalidator id="rvFirstName"
runat="server" errormessage="<-- Required"
controltovalidate="txtFirst"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td style="WIDTH: 108px">Last Name:</td>
<td><asp:textbox id="txtLast"
runat="server"></asp:textbox><font color="#ff3300"
size="4"><strong>*</strong></font></td>
<td><asp:requiredfieldvalidator id="rvLastName"
runat="server" errormessage="<-- Required"
controltovalidate="txtLast"></asp:requiredfieldvalidator></td>
</tr>
<tr>
<td colspan="2" align="center"><asp:button
id="cmdSubmit" text="Submit" runat="server"></asp:button>
</td>
</tr>
</table>
</form>
<p><font color="#ff3300" size="4">*</font> Required Field
<asp:label id="lblError" style="Z-INDEX: 101; LEFT: 656px;
POSITION: absolute; TOP: 264px"
runat="server" width="216px"></asp:label></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<asp:label id="lblResult" runat="server" width="424px"></asp:label>
</body>
</html>

2. Create the Store Procedures you will need to add a new user
- You will need to handle duplicates
- You will need to handle the adding of a new user.

a. Check for Duplicates. SP_CHECKFORDUPLICATES 


(Toggle Plain Text)
CREATE PROCEDURE sp_CheckForDuplicates
(
@UserName VARCHAR(50) = NULL,
@FirstName VARCHAR(50) = NULL,
@LastName VARCHAR(50) = NULL,
@Duplicates INT = 0
)
AS
SET @Duplicates =(SELECT COUNT(*) FROM NorthWindUsers
WHERE UserName = @UserName
OR FirstName = @FirstName AND LastName = @LastName)
RETURN @Duplicates

b. Add New User. SP_REGISTERNEWUSER


(Toggle Plain Text)

CREATE PROCEDURE sp_RegisterNewUser


(
@UserName VARCHAR(50) = NULL,
@Password VARCHAR(50) = NULL,
@FirstName VARCHAR(50) = NULL,
@LastName VARCHAR(50) = NULL
)
AS
IF @UserName IS NULL OR
@Password IS NULL OR
@FirstName IS NULL OR
@LastName IS NULL
RAISERROR('Please fill in all fields', 16, 1)
ELSE
BEGIN
INSERT INTO NorthWindUsers
(UserName, Password, FirstName, LastName)
VALUES (@UserName, @Password, @FirstName, @LastName)
IF @@error <> 0
RAISERROR('User was not added', 16, 1)
ELSE
BEGIN
DECLARE @ID int
SELECT @ID = @@IDENTITY
SELECT Count(*)
FROM NorthWindUsers
WHERE UserID = @ID
END
END
RETURN
4. Create the code behind to provide functionality to your registration page.
REGISTER.ASPX.VB
- This code behind will do several things; Validate the entries for completeness, duplication, and add
the new user.
- I test for duplicates in UserName, as well as First & Last Name.

(Toggle Plain Text)

Imports System.Web.Security ' |||||| Required Class for Authentication


Imports System.Data ' |||||| DB Accessing Import
Imports System.Data.SqlClient ' |||||| SQL Server Import
Imports System.Configuration ' |||||| Required for Web.Config appSettings |||||
Public Class Register
Inherits System.Web.UI.Page
...
...

Imports System.Web.Security ' |||||| Required Class for Authentication


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
End Sub

Private Sub cmdSubmit_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles cmdSubmit.Click
If Page.IsValid Then ' ||||| Meaning the Control Validation was
successful!
' ||||| All fields have been filled in!
If ValidateNewUser(txtUserName.Text.Trim(), txtFirst.Text.Trim(),
txtLast.Text.Trim()) Then
AddNewUser(txtUserName.Text.Trim(), txtFirst.Text.Trim(),
txtLast.Text.Trim(), txtPassword.Text.Trim())
Response.Redirect("login.aspx")
End If
End If

End Sub

Function ValidateNewUser(ByVal strAlias As String, ByVal strFirst As String,


ByVal strLast As String) As Boolean
' <summary>
' ||||| This function simply verifies that there is no existing
match on
' ||||| username (alias), and that the user has not already
registered!
' </sumary>

' ||||| Set up a Connection Object to the SQL DB


Dim MyConn As SqlConnection = New
SqlConnection(ConfigurationSettings.AppSettings("strConn"))
' ||||| Pass in the StoreProcedure or Command String, as well as
the Connection object
Dim MyCmd As New SqlCommand("sp_CheckForDuplicates", MyConn)
' ||||| Set the Command Type (Stored Procedure, Text, etc)
MyCmd.CommandType = CommandType.StoredProcedure
' ||||| Create Parameter Objects for values passed in
Dim objParam1, objParam2, objParam3 As SqlParameter
' ||||| Create a parameter to store your Return Value from the
Stored Procedure
Dim objReturnParam As SqlParameter
' ||||| Add your parameters to the parameters Collection
objParam1 = MyCmd.Parameters.Add("@UserName", SqlDbType.VarChar)
objParam2 = MyCmd.Parameters.Add("@FirstName", SqlDbType.VarChar)
objParam3 = MyCmd.Parameters.Add("@LastName", SqlDbType.VarChar)
objReturnParam = MyCmd.Parameters.Add("@Duplicates", SqlDbType.Int)
objReturnParam.Direction = ParameterDirection.ReturnValue
' ||||| Set the Parameter values to the passed in values
objParam1.Value = strAlias
objParam2.Value = strFirst
objParam3.Value = strLast

Try
' ||||| Check if Connection to DB is already open, if not,
then open a connection
If MyConn.State = ConnectionState.Closed Then
' ||||| DB not already Open...so open it
MyConn.Open()
MyCmd.ExecuteNonQuery()
End If
' ||||| Was the return value greater than 0 ???
If objReturnParam.Value > 0 Then
lblResult.Text = "UserName already exists or you are
already a registered user!"
Return False
Else
Return True
End If

' ||||| Close the Connection Closes with it


MyConn.Close()

Catch ex As Exception
lblError.Text = "Error Connecting to Database!"
End Try

End Function

Sub AddNewUser(ByVal strUser As String, ByVal strFirst As String, ByVal


strLast As String, ByVal strPass As String)

' ||||| Set up a Connection Object to the SQL DB


Dim MyConn As SqlConnection = New
SqlConnection(ConfigurationSettings.AppSettings("strConn"))
' ||||| Pass in the StoreProcedure or Command String, as well as
the Connection object
Dim MyCmd As New SqlCommand("sp_RegisterNewUser", MyConn)
' ||||| Set the Command Type (Stored Procedure, Text, etc)
MyCmd.CommandType = CommandType.StoredProcedure
' ||||| Create Parameter Objects for values passed in
Dim objParam1, objParam2, objParam3, objParam4 As SqlParameter
' ||||| Create a parameter to store your Return Value from the
Stored Procedure
Dim objReturnParam As SqlParameter
' ||||| Add your parameters to the parameters Collection
objParam1 = MyCmd.Parameters.Add("@UserName", SqlDbType.VarChar)
objParam2 = MyCmd.Parameters.Add("@FirstName", SqlDbType.VarChar)
objParam3 = MyCmd.Parameters.Add("@LastName", SqlDbType.VarChar)
objParam4 = MyCmd.Parameters.Add("@Password", SqlDbType.VarChar)
' ||||| Set the Parameter values to the passed in values
objParam1.Value = strUser
objParam2.Value = strFirst
objParam3.Value = strLast
objParam4.Value = strPass

Try
' ||||| Check if Connection to DB is already open, if not,
then open a connection
' ||||| DB not already Open...so open it
MyConn.Open()
MyCmd.ExecuteNonQuery()

' ||||| Close the Connection Closes with it


MyConn.Close()

Catch ex As Exception
lblError.Text = "Error Connecting to Database!"
End Try

End Sub
End Class

5. Final thing to do: Link the Registration Page to the Login Page
- I used a Hyperlink on the login page to do this, but you could use anything. It is just a simple <a
href="Register.aspx" ...> line of code to use for this. On that note I also send the user right back to
the login page on successful registration. This is not the ideal thing to do. It would be better to direct
them to a page that said "You are now registered! Would you like to return to the login page?" and a
means of allowing them to return to the login page. But you specific use of this may be different, so
the choice is yours.

6. Compile and run..... 

Happy coding 

Paladine
Master Poster

 Offline
793 posts
since Feb 2003

ADO.NET for Oracle


.NET data provider to direct access to Oracle database   www.devart.com

Ads by Google

Permalink

May 16th, 2005

0
Re: ASP.NET Registration Page
Nice this is good stuff Paladine. 

Miller
millers_35
Newbie Poster

 Offline
18 posts
since Apr 2005

Permalink

Jul 22nd, 2005

0
Re: ASP.NET Registration Page
Hi

I have tried to add more fields ie: Address, Phone, Email etc everything compiles ok but when
running the app it comes up with the database error (lblError) 

I have updated the Stored procedure and the database with the correct fields so i think i know it is
not that.

any way here is codebehind: 

(Toggle Plain Text)

Imports System.Web.Security ' |||| Required Class for Authentication


Imports System.Data ' |||| DB Accessing Import
Imports System.Data.SqlClient ' |||| SQL Server Import
Imports System.Configuration ' |||| Web.Config appsettings
Public Class register
Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.


<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

End Sub
Protected WithEvents txtUserName As System.Web.UI.WebControls.TextBox
Protected WithEvents rvUserName As
System.Web.UI.WebControls.RequiredFieldValidator
Protected WithEvents txtPassword As System.Web.UI.WebControls.TextBox
Protected WithEvents rvPassword As
System.Web.UI.WebControls.RequiredFieldValidator
Protected WithEvents txtFirst As System.Web.UI.WebControls.TextBox
Protected WithEvents rvFirstName As
System.Web.UI.WebControls.RequiredFieldValidator
Protected WithEvents txtLast As System.Web.UI.WebControls.TextBox
Protected WithEvents rvLastName As
System.Web.UI.WebControls.RequiredFieldValidator
Protected WithEvents cmdSubmit As System.Web.UI.WebControls.Button
Protected WithEvents lblError As System.Web.UI.WebControls.Label
Protected WithEvents lblResult As System.Web.UI.WebControls.Label
Protected WithEvents txtCompany As System.Web.UI.WebControls.TextBox
Protected WithEvents rvCompany As
System.Web.UI.WebControls.RequiredFieldValidator
Protected WithEvents txtAddress As System.Web.UI.WebControls.TextBox
Protected WithEvents rvAddress As
System.Web.UI.WebControls.RequiredFieldValidator
Protected WithEvents txtCity As System.Web.UI.WebControls.TextBox
Protected WithEvents rvCity As
System.Web.UI.WebControls.RequiredFieldValidator
Protected WithEvents txtPostCode As System.Web.UI.WebControls.TextBox
Protected WithEvents rvPostCode As
System.Web.UI.WebControls.RequiredFieldValidator
Protected WithEvents txtEmail As System.Web.UI.WebControls.TextBox
Protected WithEvents rvEmail As
System.Web.UI.WebControls.RequiredFieldValidator
Protected WithEvents txtPhone As System.Web.UI.WebControls.TextBox
Protected WithEvents rvPhone As
System.Web.UI.WebControls.RequiredFieldValidator
Protected WithEvents txtFax As System.Web.UI.WebControls.TextBox

'NOTE: The following placeholder declaration is required by the Web Form


Designer.
'Do not delete or move it.
Private designerPlaceholderDeclaration As System.Object

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub

#End Region

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load
' |||| Put user code to initialize the page here
End Sub
Private Sub cmdSubmit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmdSubmit.Click
If Page.IsValid Then ' |||| Meaning the Control Validation was
successful!
' |||| All Fileds have been filled in!
If ValidateNewUser(txtUserName.Text.Trim(), txtFirst.Text.Trim(),
txtLast.Text.Trim()) Then
AddNewUser(txtUserName.Text.Trim(), txtFirst.Text.Trim(),
txtLast.Text.Trim(), txtPassword.Text.Trim())
Response.Redirect("login2.aspx")
End If
End If
End Sub

Function ValidateNewUser(ByVal strAlias As String, ByVal strFirst As String,


ByVal strLast As String) As Boolean
' |||| This function simply varifies that there is no existing match
on
' |||| username (alias), and that the user has not already
registered!
' |||| |||| |||| |||| |||| |||| |||| |||| |||| ||||
' |||| Set up a connection object to the SQL DB
Dim MyConn As SqlConnection = New
SqlConnection(ConfigurationSettings.AppSettings("strConn"))
' |||| Pass in the StoredProcedure or Command String, as well as the
Connection object
Dim MyCmd As New SqlCommand("sp_CheckForDuplicates", MyConn)
' |||| Set the command type (stored procedure, text, etc)
MyCmd.CommandType = CommandType.StoredProcedure
' |||| Create Parameter Objects for values passed in
Dim objParam1, objParam2, objParam3, objParam5 As SqlParameter
' |||| Create a parameter to store your Return value from the stored
procedure
Dim objReturnParam As SqlParameter
' |||| Add your parameters to the parameters Collection
objParam1 = MyCmd.Parameters.Add("@UserName", SqlDbType.VarChar)
objParam2 = MyCmd.Parameters.Add("@FirstName", SqlDbType.VarChar)
objParam3 = MyCmd.Parameters.Add("@LastName", SqlDbType.VarChar)
objReturnParam = MyCmd.Parameters.Add("@Duplicates", SqlDbType.Int)
objReturnParam.Direction = ParameterDirection.ReturnValue
' |||| Set the Parameter values to the passed in values
objParam1.Value = strAlias
objParam2.Value = strFirst
objParam3.Value = strLast

Try
' |||| Check if Connection to the DB is already open , if not,
then open a connection
If MyConn.State = ConnectionState.Closed Then
' |||| DB not already open... so open it
MyConn.Open()
MyCmd.ExecuteNonQuery()
End If
' |||| Was the return value greater that 0?
If objReturnParam.Value > 0 Then
lblResult.Text = "UserName already exists or you are
already a registered user!"
Return False
Else
Return True
End If
' |||| Close the connection Closes with it
MyConn.Close()

Catch ex As Exception
lblError.Text = "Error Connecting to DataBase!"
End Try

End Function

Sub AddNewUser(ByVal strUser As String, ByVal strFirst As String, ByVal


strLast As String, ByVal strPass As String)
' |||| Set up new Connection To the SQL DB
Dim MyConn As SqlConnection = New
SqlConnection(ConfigurationSettings.AppSettings("strConn"))
' |||| Pass in the StoredProcedure or Command String, as well as the
Connection object
Dim MyCmd As New SqlCommand("sp_RegisterNewUser", MyConn)
' |||| Set the command type (Stored Procedure, Test, etc)
MyCmd.CommandType = CommandType.StoredProcedure
' |||| Create Parameter objects for values passed in
Dim objParam1, objParam2, objPAram3, objParam4, objParam5, objParam6,
objParam7, objParam8, objParam9, objParam10, objParam11 As SqlParameter
' |||| Creat an Parameter to store your return Value from the Stored
Procedure
Dim objReturnParam As SqlParameter
' |||| Add your parameters to the parameters Collection
objParam1 = MyCmd.Parameters.Add("@UserName", SqlDbType.VarChar)
objParam2 = MyCmd.Parameters.Add("@FirstName", SqlDbType.VarChar)
objPAram3 = MyCmd.Parameters.Add("@LastName", SqlDbType.VarChar)
objParam4 = MyCmd.Parameters.Add("@Password", SqlDbType.VarChar)
objParam5 = MyCmd.Parameters.Add("@Company", SqlDbType.VarChar)
objParam6 = MyCmd.Parameters.Add("@Address", SqlDbType.VarChar)
objParam7 = MyCmd.Parameters.Add("@City", SqlDbType.VarChar)
objParam8 = MyCmd.Parameters.Add("@PostCode", SqlDbType.VarChar)
objParam9 = MyCmd.Parameters.Add("@Email", SqlDbType.VarChar)
objPAram10 = MyCmd.Parameters.Add("@Phone", SqlDbType.VarChar)
objParam11 = MyCmd.Parameters.Add("@Fax", SqlDbType.VarChar)
' |||| Set the Parameter values to the passed in values
objParam1.Value = strUser
objParam2.Value = strFirst
objPAram3.Value = strLast
objParam4.Value = strPass

Try
' |||| Check if connection is already open
MyConn.Open()
MyCmd.ExecuteNonQuery()
MyConn.Close()
Catch ex As Exception
lblError.Text = "Error Connecting to DataBase!"
End Try
End Sub
End Class

You might also like