动态创建的按钮如何移除

4
我想通过在TextBox中给定范围,动态地创建多个
问题是,当我输入范围例如(3)时,它会创建3个按钮。但当我给出比之前给出的范围更小的范围例如(2)时,它不会显示2个按钮而是显示之前的3个按钮。我的代码可以为大于之前范围的范围工作,但在新范围小于之前范围时失败。
以下是我的代码:
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);
    }
}

为什么你要给Button数组取名叫做textBoxes - Selman Genç
首先,我想创建文本框。所以我忘记改变名称了。 - Loyal
3个回答

3

您没有删除先前的控件。您需要将它们存储在一个数组中,在创建新的控件之前删除它们:

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);
        }
    }
}

我没有测试过这段代码,但是我希望你能理解其中的思路。


2

这不是失败了,而是之前创建的按钮重叠在一起了。


是的,但如何去除重叠。 - Loyal

0

首先移除已经存在的按钮。可以通过在它们的名称中保持一个模式或使用全局列表等方式来跟踪它们,或者通过其他方式。每当您进入函数时,都要移除所有当前存在的按钮,并创建新的按钮。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接