Windows Forms: How to Create a Random Password Generator in C#

This post shows you How to Create a Random Password Generator in C# Windows Forms Application.

Sometimes you need to create default password, for example reset password, you can do it by following way.

C# password generator alphanumeric.

Creating a simple user interface allows you to generate random password with options lower case, upper case, numeric or specical character as shown below.

c# password generator

Next, Create a PasswordGenerator method allows you to generate password.

public string PasswordGenerator(bool lowerCase, bool upperCase, bool mumberic, bool specialCharacter, int length)
    char[] password = new char[length];
    string charSet = "";
    System.Random _random = new Random();
    if (lowerCase)
        charSet += LOWER_CASE;
    if (upperCase)
        charSet += UPPER_CASE;
    if (mumberic)
        charSet += NUMBERIC;
    if (specialCharacter)
        charSet += SPECIAL_CHARACTER;
    for (int i = 0; i < length; i++)
        password[i] = charSet[_random.Next(charSet.Length - 1)];
    return string.Join(null, password);

Each option is selected we will concatenate, then generate random string in c#.

const string LOWER_CASE = "abcdefghijklmnopqursuvwxyz";
const string NUMBERIC = "1234567890";
const string SPECIAL_CHARACTER = @"[email protected]#$%^&*()+=-";

Adding a click event handler to the Generate button allows you to generate password.

//c# text generator
private void btnGenerate_Click(object sender, EventArgs e)
        txtPassword.Text = PasswordGenerator(chkLowerCase.Checked, chkUpperCase.Checked, chkNumeric.Checked, chkSpecical.Checked, int.Parse(txtPasswordLength.Text));
    catch (Exception ex)
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);

You can easily choose how to create a password that combines lower case letters, upper case letters, numbers, or special characters.