How to remove buttons created dynamically

I want to dynamically create a number Buttonby specifying a range in TextBox.

The problem is that when I enter a range, for example (3). It creates 3 buttons, but then when I give the range less than the range indicated before, for example, (2). it does not show me 2 buttons, it shows me the previous 3 buttons. My code runs in a range that exceeds the previous range, but it fails when the new range is smaller 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);
    }
}
+4
source share
3 answers

You do not delete previous controls. You must save them in an array and then delete them before creating 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);
        }
    }
}

, , .

+3

, , , .

+2

delete existing buttons first. You can track them by storing the template in your names or by having a global list, etc. or another way. when you enter the function, delete all the buttons present and create new ones.

0
source

Source: https://habr.com/ru/post/1525925/


All Articles