Evorage
Evorage

Reputation: 503

C# Forms radiobutton clicked multiple times while checked

I have two radio buttons side by side in my forms and one of them generates a random password when clicked which is fine but how do I get it to, if clicked again (while already checked) it runs the code again, this isn't an issue with my code so none is required, its more of a question with visual studio's winforms radio button. Thanks in advance

private void NAPOCustom_CheckedChanged(object sender, EventArgs e) //Weird radiobutton name i know
        {
            NAPasswordE.Clear(); //text box which generation password goes into
                string validChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*?_-";
            Random random = new Random();
            char[] chars = new char[12];
            for (int i = 0; i < 12; i++)
            {
                chars[i] = validChars[random.Next(0, validChars.Length)];
            }
            NAPasswordE.Text = new string(chars);
        }

I click the radiobutton

Desired Output: random string (this works)

I click the same radiobutton again

Desired Output: random string but different to first one (doesnt work)

Upvotes: 0

Views: 308

Answers (1)

Idle_Mind
Idle_Mind

Reputation: 39122

You can handle both the Click() and CheckChanged() event. Technically it will produce two passwords, but in this case I don't think it really matters. Move your password generation code out to a separate method and call that from both event handlers. Also move your Random out to class level.

Something like:

private Random random = new Random();

private void NAPOCustom_Click(object sender, EventArgs e)
{
    RandomPassword();
}

private void NAPOCustom_CheckedChanged(object sender, EventArgs e)
{
    if (NAPOCustom.Checked)
    {
        RandomPassword();
    }
}

private void RandomPassword()
{           
    string validChars = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*?_-";
    char[] password = validChars.ToCharArray().OrderBy(x => random.Next()).Take(12).ToArray();            
    NAPasswordE.Text = new string(password);
}

Upvotes: 1

Related Questions