c# - 如何删除动态创建的按钮

标签 c# .net

我想通过在 TextBox 中提供范围来动态地 创建多个 Button

问题是当我输入范围时,例如 (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);
    }
}

最佳答案

您并没有删除以前的控件。您必须将它们存储在一个数组中,然后在创建新数组之前删除它们:

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

我还没有测试过这段代码,但我希望你明白了。

关于c# - 如何删除动态创建的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21645270/

相关文章:

c# - 使用列名检索数据的 MySQL 查询

c# - 闭包和 java 匿名内部类

javascript - 从 C# 中的代码隐藏将 JavaScript 注入(inject)到链接按钮

c# - LINQ - 如何忽略 where 中的空列表

c# - 如何在 C# 中追加 xml 文件?

c# - 椰枣培养物

c# - 远程服务器声明表不存在

.net - 为什么我的 boolean 值 0 返回 true?

c# - 所描述的数据模型的导航属性的实现

C#鼠标悬停时更改表格行颜色