[Solved] How to make a button in C# Make a text file and add the result of a textbox to it and then show it in the program? [closed]


Add a ListBox to your form and call it listBox1. Then add a click event to button1, and do something like:

private void button1_Click(object sender, EventArgs e) {
    int length;

    // We use TryParse to make sure it is a number, otherwise
    // we tell the user and return;.
    if (!int.TryParse(textBox2.Text, out length)) {
        MessageBox.Show("Not a number!");
        return;
    }

    // Make a random string
    string myString = RandomString(length);

    // Show it in the text box
    textBox1.Text = myString;

    // ... and in the listbox
    listBox1.Items.Add(myString);
}

The function for a random string could look like this:

string RandomString(int length) {
    string options = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!#%&/()=?";

    StringBuilder str = new StringBuilder(length);
    Random random = new Random();

    // Add the characters one by one
    for (int i = 0; i < length; i++) {
        // Get a random index in our character options string.
        int randomIndex = random.Next(options.Length);

        // Add the random character
        str.Append(options[randomIndex]);
    }

    // Make a string of the StringBuilder and return it.
    return str.ToString();
}

1

solved How to make a button in C# Make a text file and add the result of a textbox to it and then show it in the program? [closed]