Generate random password in using c# and save in database

Generate random password in using c# :-In this I going to show how to do registration and generate random password and save it in database. We will also send the mail to user's email for confirmation of UserID and password.

This is very pretty step to generate random password of 8-digits, you can generate any digit of password depends on you. Alright let's get start.

How to generate random password in using c# and save in databse

Create table

      [id] [int] Primary key IDENTITY(1,1) NOT NULL,
      [username] [varchar](50) ,
      [email] [varchar](50) ,
      [password] [varchar](20)

First of all add the database connection within web.config file

    <add name="Mycon" connectionString="initial catalog =Test11718; data source=SANJAY\SQL2012; integrated security=true" providerName="System.Data.SqlClient"/>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>


Add a webform which name will be user-registration.aspx In this take two text-box one label and one button to save a record in database.

     Read More: How to upload image in gridview in using c#

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="user-registration.aspx.cs" Inherits="user_registration" %>

<!DOCTYPE html>

<html xmlns="">
<head runat="server">

    <form id="form1" runat="server">
                    <b>Send Password to Email and save it in database</b>
                    <td class="style1">Username:</td>
                        <asp:TextBox ID="txt_name" runat="server"></asp:TextBox>
                    <td class="style1">Email:</td>
                        <asp:TextBox ID="txt_Email" runat="server"></asp:TextBox>
                        <asp:Label ID="lblMessage" runat="server"></asp:Label>
                     <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit"/>

Now come on the user-registration.aspx.cs   and add each and every necessary namespaces.

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Net;

public partial class user_registration : System.Web.UI.Page
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mycon"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    public static string CreateRandomPassword(int PasswordLength)
        string _allowedChars = "0123456789";
        Random randNum = new Random();
        char[] chars = new char[PasswordLength];
        int allowedCharCount = _allowedChars.Length;
        for (int i = 0; i < PasswordLength; i++)
            chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
        return new string(chars);
    protected void Button1_Click(object sender, EventArgs e)
        string pwd = CreateRandomPassword(8);
        SqlCommand cmd = new SqlCommand("insert into employee(username,email,password) values (@username,@email,@password)", con);
        cmd.Parameters.AddWithValue("@username", txt_name.Text);
        cmd.Parameters.AddWithValue("@email", txt_Email.Text);
        cmd.Parameters.AddWithValue("@password", pwd);
        int i = cmd.ExecuteNonQuery();

    public void sendmail()
        SqlCommand cmd_cus = new SqlCommand("select email from employee where email=@Email", con);
        cmd_cus.Parameters.AddWithValue("@Email", txt_Email.Text);
        SqlDataReader dr = cmd_cus.ExecuteReader();
        if (dr.HasRows)
        string strNewPassword = CreateRandomPassword(8);
        string me = dr["email"].ToString();
        MailMessage msg = new MailMessage();
        msg.From = new MailAddress("[email protected]");
        msg.Subject = "Job Portal:Login Detail for your Account";
        msg.Body = "Your password is:-" + strNewPassword + "<br />" + "Your user name same as you email:- " + me;
        msg.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "";
        smtp.Port = 587;
        smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "yourpassword");
        smtp.EnableSsl = true;
        lblMessage.Text = "Email Sent Successfully";
        lblMessage.ForeColor = System.Drawing.Color.ForestGreen;

In above tutorial I explained "how to generate random password in using c# and save in database"  for the domain name. if you have another account like ,  then you may have to change port number and little bit code.

After done all these step , may you face a problem like this "Authentication the Server Response was 5.5.1 Authentication required in gmail" . In this case follow the given steps.

1. Login to your gmail account.
2. Visit this page and click on button to allow access.
3. Visit this page and enable access for less secure apps.

Read our previous post


Post a Comment

Post a Comment

Previous Post Next Post