Friday, 27 December 2013

Change password using asp.net



Introduction: Hello friends, in this article i will explain that how we can change the password after login, in asp.net.This article is very useful for the all the .net developer.

Implementation: create a new website add a page. Drag and drop three textboxes and two buttons  from the toolbox inside the  <body> body tag at the .aspx page.  Below  i am giving the complete code for the html page and .cs page. 

Code for default.aspx page
<div>
    <table style="width: 91%; height: 97px;" class="tbl_reg_form">
        <tr>
            <td>
                Old Password</td>
            <td>
                <asp:TextBox ID="txt_old_pwd" runat="server" CssClass="input" TextMode="Password"></asp:TextBox>
                &nbsp;<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                    ControlToValidate="txt_old_pwd" ErrorMessage="Required">*</asp:RequiredFieldValidator>
            </td>
        </tr>
      
        <tr>
            <td>
                New Password</td>
            <td>
                <asp:TextBox ID="txt_new_pwd" runat="server" CssClass="input" TextMode="Password"></asp:TextBox>
                &nbsp;<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
                    ControlToValidate="txt_new_pwd" ErrorMessage="Required">*</asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td style="height: 29px">
                Confirm Password</td>
            <td style="height: 29px">
                <asp:TextBox ID="txt_confirm_pwd" runat="server" CssClass="input" TextMode="Password"></asp:TextBox>
                &nbsp;<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
                    ControlToValidate="txt_confirm_pwd" ErrorMessage="Required">*</asp:RequiredFieldValidator>
                &nbsp;</td>
        </tr>
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    <asp:CompareValidator ID="CompareValidator1" runat="server"
                        ControlToCompare="txt_new_pwd" ControlToValidate="txt_confirm_pwd"
                        ErrorMessage="CompareValidator">New Password does not match</asp:CompareValidator>
                </td>
            </tr>
        <tr>
            <td>
                &nbsp;</td>
            <td>
                <asp:Button ID="btn_submit" runat="server"
                    Text="Change Password" onclick="btn_submit_Click" />
                &nbsp;<asp:Button ID="btn_cancel" runat="server" CausesValidation="False"
                     Text="Reset" onclick="btn_cancel_Click" />
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;</td>
            <td>
                <asp:Label ID="lbl_msg" runat="server" Text=""></asp:Label>
            </td>
        </tr>
    </table>
    </div>

Code for default.aspx.cs page

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Drawing;  
public partial class _Default : System.Web.UI.Page
{
  
    SqlCommand cmd;
    DataTable dt;
    SqlConnection con = new SqlConnection();
    SqlDataAdapter adp;
 
    protected void Page_Load(object sender, EventArgs e)
    {



        // here i am declare connection 
        con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
        con.Open();
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
     
     
    }

    protected void btn_submit_Click(object sender, EventArgs e)
    {

        if (con.State == ConnectionState.Closed)
        { con.Open(); }
        try
        {
            // here inside the cmd  definning sql query to select the password from the table
            adp = new SqlDataAdapter("select password from REGISTRATION where  password=?password and username=?username", con);
            // Passing parameters
            adp.SelectCommand.Parameters.AddWithValue("?password", txt_old_pwd.Text);
            //  This program will be working when the user will login inside the application so you can pass parameter
            // named username via session or cokkie, here i am using session
            adp.SelectCommand.Parameters.AddWithValue("?username", Session["username"].ToString());
            dt = new DataTable();

            adp.Fill(dt);
            // Here checked the enter old password is available inside the database or no
            // If the old password not correct entered by the user, then it will enter inside the if condition
            if (dt.Rows.Count == 0)
            {
                // it will display message inside the lable
                lbl_msg.ForeColor = Color.Red;
                lbl_msg.Text = "Old Password does not match";
                clr_rec();
                return;
            }
            // If the old password  correct entered by the user, then it will enter inside the else condition
            else
            {

                // here inside the cmd  definning sql query to update the password from the table
                cmd = new SqlCommand("update REGISTRATION set password=?password where   username=?username", con);
                // Passing parameters
                cmd.Parameters.AddWithValue("?password", txt_new_pwd.Text);
                //  This program will be working when the user will login inside the application so you can pass parameter
                // named username via session or cokkie, here i am using session.
                cmd.Parameters.AddWithValue("?username", Session["username"].ToString());
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                con.Close();
                // it will display message inside the lable that password has changed Successfully
                lbl_msg.Text = "Password has changed Successfully";
                clr_rec();

            }
        }
        catch { }
    }
    protected void btn_cancel_Click(object sender, EventArgs e)
    {
        clr_rec();
    }

    private void clr_rec()
    {
        // this method will crear all the mentioned textboxes.
        txt_confirm_pwd.Text = "";
        txt_new_pwd.Text = "";
        txt_old_pwd.Text = "";
    }
}


Connectionstring

<connectionStrings>
  <add name="cnn" connectionString="Data source=BHARAT-HP;database=practice;uid=sa;pwd=1234;Min Pool Size=100;Max Pool Size=1000;Connect Timeout=10"/>
  </connectionStrings>

Database Script

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[REGISTRATION]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[REGISTRATION](
      [id] [bigint] IDENTITY(1,1) NOT NULL,
      [username] [varchar](50) NULL,
      [password] [varchar](50) NULL,
 CONSTRAINT [PK_REGISTRATION] PRIMARY KEY CLUSTERED
(
      [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END

See the output inside the image below





Conclusion: In above code, I have been explained that how  we can change password  in asp.net. This code is very helpful for every .net developer. Gud bye and take care developers. We will come back shortly with the new article.



Regards
Using Asp.net





2 comments: