how to remove buttons created dynamically

.net, c#

Solution

You aren't removing the previous controls. You have to store them in an array then removing them before creating the new ones:

class Form1 : Form {
    private Button[] _textBoxes;

    private void button2_Click(object sender, EventArgs e) {
        int number = int.Parse(textBox3.Text);
        if(_textBoxes != null) {
            foreach(Button b in _textBoxes)
                this.Controls.Remove(b);
        }

        _textBoxes = new Button[number];
        int location = 136;

        for (int i = 0; i < textBoxes.Length; i++) {
            location += 81;
            var txt = new Button();
            _textBoxes[i] = txt;
            txt.Name = "text" + i.ToString();
            txt.Text = "textBox" + i.ToString();
            txt.Location = new Point(location, 124);
            txt.Visible = true;
            this.Controls.Add(txt);
        }
    }
}

I haven't tested this code but I hope you get the idea.

Problem

I want to create number of `Button`s dynamically by giving the range in a `TextBox`. The Problem is that when i enter the range e.g (3). It creates 3 buttons but then when i give the range less than the range given before e.g (2). it does not show me 2 buttons it shows me the previous 3 buttons. My code works for the range greater than the previous range but it fails when the new range is less than the previous range. Here is my code: ``` private void button2_Click(object sender, EventArgs e) { int number = int.Parse(textBox3.Text); Button[] textBoxes = new Button[number]; int location = 136; for (int i = 0; i < textBoxes.Length; i++) { location += 81; var txt = new Button(); textBoxes[i] = txt; txt.Name = "text" + i.ToString(); txt.Text = "textBox" + i.ToString(); txt.Location = new Point(location, 124); txt.Visible = true; this.Controls.Add(txt); } } ```

Original source