删除在按钮单击时动态创建的文本框
问题描述:
我尝试使用列表动态创建文本框.我现在需要的是,如何通过点击重置按钮重置我创建的所有文本框.
I have tried creating textboxes dynamically using lists. All i need now is, how can i reset all text boxes that i have created by hitting a reset button.
以下是我的代码:
public void button2_Click_1(object sender, EventArgs e)
{
int number = Convert.ToInt32(textBox2.Text);
List<TextBox> inputTextBoxes;
inputTextBoxes = new List<TextBox>();
for (int i = 1; i <= number; i++)
{
Label labelInput = new Label();
TextBox textBoxNewInput = new TextBox();
labelInput.Text = "Activity No: " + i;
labelInput.Location = new System.Drawing.Point(30, textBox2.Bottom + (i * 40));
labelInput.AutoSize = true;
textBoxNewInput.Location = new System.Drawing.Point(labelInput.Width+60, labelInput.Top - 3);
inputTextBoxes.Add(textBoxNewInput);
this.Controls.Add(labelInput);
this.Controls.Add(textBoxNewInput);
}
}
答
将下面一行移到事件处理函数外(函数外但类内)
Move the following line outside the event handler function (outside the function but inside the class)
List
然后点击重置按钮
private void btnReset_Click(object sender, EventArgs e){foreach(输入文本框中的文本框txt){this.Controls.Remove(txt);}inputTextBoxes.Clear();}
更正了 foreach 循环中的类类型(从按钮到文本框)