我想通过在 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/