从动态界面中删除控件

时间:2012-04-20 22:40:52

标签: c# .net visual-studio-2010 dynamic

我正在开展一个c#运动项目,以发展我的技能和学习新事物。我已经创建了一个动态界面,其中包含一些控件..当表单加载时,它启动一个numericUpDown和一个Button。当用户在数字向上选择一个数字并单击该按钮时,它将生成尽可能多的文本框,具体取决于在numericUpDown上选择的数字,它还会在生成的文本框旁边生成一个删除按钮。我在用户点击删除按钮时删除文本框时遇到问题

这是我的代码:

//生成文本框和按钮

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

任何想法都会非常感激

2 个答案:

答案 0 :(得分:1)

尝试类似

的内容
foreach (var control in textboxAssesmentName)
{
    this.Controls.Remove(control);
}

您现有的代码没有任何意义。

另见
http://msdn.microsoft.com/en-us/library/82785s1h%28v=vs.80%29.aspx

答案 1 :(得分:0)

我建议您使用Tag的{​​{1}}属性来存储与其关联的Button。要将它放在代码中,请在循环中插入以下行:

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