Introduction:
In this article I am going to explain with example how to create change
password page/ form in asp.net using both
the C# and VB.Net languages and using Stored procedure and Sql server as a back end database.
Description: In this article you will learn the following:
- How to create change password form and update the password.
- How to check credentials i.e. username and password from the Sql server database
- How to use output parameter in stored procedure to return value.And how to get/read the return output in the code behind.
- How to use COLLATE Latin1_general_CS_AS to check for case sensitive match.
In previous related articles I explained How to create Login page/form and check username,password in asp.net using stored procedure and sql server database and How to encrypt and decrypt username,password and store in Sql Server database using asp.net and Recover and reset the forgot/lost password using reset password link in email id and Pass parameter to stored procedure using SqlDataAdapter and check login and Ajax ModalPopupExtender example to open login form in popup window and Create drop down menu for login and signup using jQuery and CSS in asp.net and Convert Rupees,Currency or Numbers to Words.
The concept is simple. We first need to check the entered username and password against the database and if matched then the new password will overwrite the old password otherwise message will be displayed "Wrong Username/Password"
Implementation: Let’s create an asp.net
application to understand the concept.
- First of all create a Sql server database and name it "MyDataBase" and create a table with the following fields and name it "Login_Tb"
Column
Name
|
Data
Type
|
Id
|
Int( Primary Key. So set Is Identity=True)
|
UserName
|
varchar(100)
|
Password
|
varchar(100)
|
- Add dummy username e.g. admin and password e.g. demo in the table.
- Then create a Stored Procedure to check existing username and password and change the password as:
CREATE PROCEDURE Change_Pwd_sp
(
@username VARCHAR(100),
@old_pwd VARCHAR(50),
@new_pwd VARCHAR(50),
@status int OUTPUT
)
AS
BEGIN
IF EXISTS(SELECT
* FROM Login_Tb
WHERE UserName COLLATE
Latin1_general_CS_AS=@username AND [PASSWORD] COLLATE
Latin1_general_CS_AS=@old_pwd)
BEGIN
UPDATE Login_Tb SET
[PASSWORD]=@new_pwd WHERE
UserName=@username
SET @status=1
END
ELSE
BEGIN
SET @status=0
END
END
RETURN @status
In this stored procedure first the entered username and password will be checked from the database and if matched then the new password will overwrite the old password otherwise message will be displayed "Wrong Username/Password". we are using Output parameter to return the status i.e 1 for success and 0 for failure. Also Notice that in this stored procedure i have also used the COLLATE Latin1_general_CS_AS to check for the exact username and password match because it is used to make the sql queries case sensitive. e.g. if the username is admin and password is demo then if user enters Admin in username or Demo in password field then it will not match and it will not update the username and password.
- Now in the web.config file create the connection string to connect our asp.net web application with the Sql server database as.
<connectionStrings>
<add name="conStr" connectionString="Data Source=lalit;Initial Catalog=MyDataBase;Integrated
Security=True"/>
</connectionStrings>
Note:
Replace the Data Source and the Initial Catalog(database name) as per your application.
HTML Source Code:
- In the <Form> tag of the design page(.aspx) design the page as:
<div>
<fieldset style="width:350px;">
<legend>Change password example in asp.net</legend>
<table>
<tr>
<td>User Name: * </td>
<td>
<asp:TextBox ID="txtUserName"
runat="server"></asp:TextBox><br />
<asp:RequiredFieldValidator
ID="rfvuserName"
runat="server"
ErrorMessage="Please
enter User Name" ControlToValidate="txtUserName"
Display="Dynamic"
ForeColor="Red"
SetFocusOnError="True"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Old Password: * </td>
<td>
<asp:TextBox ID="txtOldPwd"
runat="server"
TextMode="Password"></asp:TextBox><br />
<asp:RequiredFieldValidator
ID="rfvOldPwd"
runat="server"
ErrorMessage="Please
enter old password" ControlToValidate="txtOldPwd"
Display="Dynamic"
ForeColor="Red"
SetFocusOnError="True"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>New Password: * </td>
<td>
<asp:TextBox ID="txtNewPwd"
runat="server"
TextMode="Password"></asp:TextBox><br />
<asp:RequiredFieldValidator
ID="rfvNewPwd"
runat="server"
ErrorMessage="Please
enter new password" ControlToValidate="txtNewPwd"
Display="Dynamic"
ForeColor="Red"
SetFocusOnError="True"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>Confirm Password: * </td>
<td>
<asp:TextBox ID="txtConfirmPwd"
runat="server"
TextMode="Password"></asp:TextBox><br />
<asp:RequiredFieldValidator
ID="rfvConfirmPwd"
runat="server"
ErrorMessage="Please
re-enter password to confirm"
ControlToValidate="txtConfirmPwd"
Display="Dynamic"
ForeColor="Red"
SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="cmvConfirmPwd"
runat="server"
ControlToCompare="txtNewPwd"
ControlToValidate="txtConfirmPwd"
Display="Dynamic"
ErrorMessage="New
and confirm password didn't match"
ForeColor="Red"
SetFocusOnError="True"></asp:CompareValidator>
</td>
</tr>
<tr>
<td>
</td><td>
<asp:Button ID="btnSubmit"
runat="server"
Text="Change
Password"
onclick="btnSubmit_Click"
/></td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblStatus"
runat="server"
Text=""></asp:Label>
</td>
</tr>
</table>
</fieldset>
</div>
Note: I have used the RequiredFieldValidator and CompareValidator validation controls to validate the username and password field.
Asp.Net C# code to create Change password form/page
- In the code behind file (.aspx.cs) write the following code on change pass word as:
First of all include the
following namespaces:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
then write the code as:
protected void btnSubmit_Click(object
sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
SqlCommand cmd = new SqlCommand("Change_Pwd_sp", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@username",
txtUserName.Text.Trim());
cmd.Parameters.AddWithValue("@old_pwd", txtOldPwd.Text.Trim());
cmd.Parameters.AddWithValue("@new_pwd",
txtNewPwd.Text.Trim());
cmd.Parameters.Add("@Status",
SqlDbType.Int);
cmd.Parameters["@Status"].Direction
= ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
//read the return value (i.e status) from the stored procedure
int retVal= Convert.ToInt32(cmd.Parameters["@Status"].Value);
int retVal= Convert.ToInt32(cmd.Parameters["@Status"].Value);
if (retVal == 1)
{
lblStatus.Text = "Password has been
changed successfully";
// Or show in messagebox using:
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message",
"alert('Password has been changed successfully');", true);
}
else
{
lblStatus.Text = "Wrong old
username/password. Please re-enter.";
// Or show in messagebox using:
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message",
"alert('Wrong username/password. Please re-enter.');", true);
}
}
catch (Exception
ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(),
"Message", "alert('Oops!! following error occured : " +
ex.Message.ToString() + "');", true);
// Response.Write("Oops!! following error
occured: " +ex.Message.ToString());
}
}
Asp.Net VB Code to create Change password form/page
- In the code behind file (.aspx.vb) write the following code on change pass word as:
First of all import the
following namespaces:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Then write the code as:
Protected Sub btnSubmit_Click(sender As
Object, e As
System.EventArgs) Handles
btnSubmit.Click
Try
Dim con As
New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
Dim cmd As
New SqlCommand("Change_Pwd_sp", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@username",
txtUserName.Text.Trim())
cmd.Parameters.AddWithValue("@old_pwd",
txtOldPwd.Text.Trim())
cmd.Parameters.AddWithValue("@new_pwd",
txtNewPwd.Text.Trim())
cmd.Parameters.Add("@Status",
SqlDbType.Int)
cmd.Parameters("@Status").Direction
= ParameterDirection.Output
con.Open()
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
'read the return value (i.e status) from the stored procedure
Dim retVal As Integer = Convert.ToInt32(cmd.Parameters("@Status").Value)
Dim retVal As Integer = Convert.ToInt32(cmd.Parameters("@Status").Value)
If retVal = 1 Then
lblStatus.Text = "Password has been
changed successfully"
' Or show in messagebox using:
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message",
"alert('Password has been changed successfully');", true);
Else
lblStatus.Text = "Wrong old
username/password. Please re-enter."
' Or show in messagebox using:
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message",
"alert('Wrong username/password. Please re-enter.');", true);
End If
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Oops!!
following error occured : " & ex.Message.ToString() & "');", True)
' Response.Write("Oops!! following error
occured: " +ex.Message.ToString());
End Try
End Sub
Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates."
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates."
12 comments
Click here for commentssir, i want to create inbox like gmail...
Replyplz help me to get the coding for that
hello sivakumar ck..check the article: Ajax TabContainer example to create multiple tabs/panels in asp.net
Replyhttp://www.webcodeexpert.com/2013/08/ajax-tabcontainer-example-to-create.html.
You will get the idea. You can place gridview on each tab/panel and bind appropriate data from the database.
hello i have tried out this code and this code is returning status 1 but password is not getting updated please suggest
ReplyHi, have you followed the article properly? i suggest you to recheck your code and try once again as this code is completely tested and working code..if still you face error then let me know..i will help you to sort out your problem..
ReplySir i have some problem in making login page for multiple users and connect it with sql server db i mean i making a login page by which three users which are stored in db are looged in through it ......i m working in vb.net 2008
ReplyHi, what problem you are facing? let me know and i will help you to sort out that problem.
ReplyHello Lalit Raghuvanshi can you help me deal my project problem?? It is a ASP.net VB language.
ReplyHello Lalit Raghuvanshi, can you help me for my assignment?? It is a ASP.net VB language assignment.
ReplySir, i m having this error: Exception Details: System.InvalidOperationException: WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).
Replyand m not able to understand what it is. i checked the code all good
Hello Bipika Amatya, check the below mentioned link to sort out your problem.
Replyhttp://www.webcodeexpert.com/2013/06/how-to-solve-webforms.html
Sir can u please tell us the code in which a data set is used as we hav been using a data set... we are working with visual studio 2010, asp.net with c# and my sql..
Replynot getting errors but values are not inserting in table
ReplyIf you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..