How To Generate Random Passwords In ASP. NET

In this article, we will learn how to generate random passwords In ASP. NET

First, we create the aspx page and use the following code in the page :.

<form id="form1" runat="server">
<div>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Generate Password" OnClick="Button1_Click" />
    <br />
    <br />
    <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Italic="True"
        Font-Names="Arial"></asp:Label>
</div>
</form>

 

The simple method is shown below. This is Code behind the page aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing.Design;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    public static string CreateRandomPassword(int PasswordLength)
    {
        string _allowedChars = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
        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)
    {
         Label1.Text =  CreateRandomPassword(8);
    }
}

 

OUTPUT

genrate-random-passwords-in-asp-net-1

When you click Generate Password button it will generate new random password.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories