从动态界面中删除控件
本文关键字:删除 控件 界面 动态 | 更新日期: 2023-09-27 18:31:53
我正在做一个 C# 练习项目,以发展我的技能和学习新事物。 我创建了一个动态界面,它由几个控件组成。 加载表单时,它会以数字UpDown和Button启动。 当用户在数字上下选择一个数字并单击按钮时,它将生成尽可能多的文本框,具体取决于在数字上选择的数字Updown,它也在生成的文本框旁边生成一个删除按钮。当用户单击"删除"按钮时,我无法删除文本框
这是我拥有的代码:
生成文本框和按钮
private void AssessmentButton_Click(object sender, EventArgs e)
{
int length = (int)this.NoAssesmentBoxlv4.Value;
for (int i = 0; i < length; i++)
{
textboxAssesmentName.Add(new TextBox());
var p = new System.Drawing.Point(110, 260 + i * 25);
(textboxAssesmentName[i] as TextBox).Location = p;
(textboxAssesmentName[i] as TextBox).Size = new System.Drawing.Size(183, 20);
this.Lv4Tab.Controls.Add(textboxAssesmentName[i] as TextBox);
buttoRemove.Add(new Button());
(buttoRemove[i] as Button).Location = new System.Drawing.Point(380, 260 + i * 25);
(buttoRemove[i] as Button).Text = @"x";
(buttoRemove[i] as Button).BackColor = Color.Red;
(buttoRemove[i] as Button).ForeColor = Color.White;
(buttoRemove[i] as Button).Size = new System.Drawing.Size(22, 23);
this.Lv4Tab.Controls.Add(buttoRemove[i] as Button);
(buttoRemove[i] as Button).Click += this.buttoRemove_click;
}
}
这是删除按钮的点击解决方案:(此方法不编译)
private void buttoRemove_click(object sender, EventArgs e)
{
foreach (Object obj in textboxAssesmentName)
{
// THIS LINE DOES NOT COMPILE!!!
this.Controls.Remove(textboxAssesmentName.Remove);
}
}
任何想法将不胜感激
尝试类似
foreach (var control in textboxAssesmentName)
{
this.Controls.Remove(control);
}
您现有的代码没有任何意义。
参见
http://msdn.microsoft.com/en-us/library/82785s1h%28v=vs.80%29.aspx
我建议你使用Button
的Tag
属性来存储与之关联的TextBox
。若要将其放入代码中,请在循环中插入以下行:
(buttoRemove[i] as Control).Tag = textboxAssesmentName[i];
然后,事件处理程序将如下所示:
private void buttoRemove_click(object sender, EventArgs e)
{
this.Controls.Remove((sender as Control).Tag as Control);
}
编辑:这是我编写代码的方式(不包括拼写错误)。
private void AssessmentButton_Click(object sender, EventArgs e)
{
int length = (int)this.NoAssesmentBoxlv4.Value;
for (int i = 0; i < length; i++)
{
TextBox t = new TextBox();
System.Drawing.Point p = new System.Drawing.Point(110, 260 + i * 25);
t.Location = p;
t.Size = new System.Drawing.Size(183, 20);
Button b = new Button();
b.Location = new System.Drawing.Point(380, 260 + i * 25);
b.Text = @"x";
b.BackColor = Color.Red;
b.ForeColor = Color.White;
b.Size = new System.Drawing.Size(22, 23);
b.Click += new System.EventHandler(this.buttoRemove_click);
this.Lv4Tab.Controls.Add(t);
this.Lv4Tab.Controls.Add(b);
textboxAssesmentName.Add(t);
buttoRemove.Add(b);
}
}
private void buttoRemove_click(object sender, EventArgs e)
{
Control b = sender as Control;
Control t = b.Tag as Control;
this.Lv4Tab.Controls.Remove(t);
this.Lv4Tab.Controls.Remove(b);
textboxAssesmentName.Remove(t);
buttoRemove.Remove(b);
}