动态添加时,删除标记为按钮的文本框

时间:2014-02-27 06:58:56

标签: c# winforms dynamic-controls

以下是代码。在这里,我在按钮点击时动态添加2个文本框和一个按钮。我将文本框标记为动态创建按钮(删除)。所以点击删除按钮我需要删除标记到它的文本框。但只有1个文本框被删除而不是另一个。我无法找出原因。

   private void button1_Click(object sender, EventArgs e)
    {
     int c=0;   
int v;
v = c++;
  panel1.VerticalScroll.Value = VerticalScroll.Minimum;

Button btn = new Button();
btn.Name = "btn" + v;
btn.Text = "Remove";
btn.Location = new Point(370, 5 + (30 * v));
btn.Click += new EventHandler(btn_Click);


TextBox txt = new TextBox();
txt.Name = "TextBox" + v;
txt.Location = new Point(30, 5 + (30 * v));
txt.Tag = btn;


TextBox txt1 = new TextBox();
txt1.Name = "TextBox2" + v;
txt1.Location = new Point(170, 5 + (30 * v));
txt1.Tag = btn;


panel1.Controls.Add(txt);
 panel1.Controls.Add(txt1);

panel1.Controls.Add(btn);

}

private void btn_Click(object sender, EventArgs e)
 {


  //to remove control by Name
    foreach (Control item in panel1.Controls.OfType<Control>())
 {
     if (item.Tag == sender || item == sender)
        panel1.Controls.Remove(item);
 }
}

1 个答案:

答案 0 :(得分:0)

从列表中删除项目时,请尝试使用foreach,而不是使用for,然后向后迭代。以下问题有一些与本文类似的解决方案:

Safely Removing DataRow In ForEach

所以,像这样(我没有测试过这段代码,但这是一般的想法):

// Iterate over each control to remove, and remove it
for (int i = panel1.Controls.Count - 1; i >= 0; i--) 
{
    var item = panel1.Controls[i];
    if (item.Tag == sender || item == sender)
        panel1.Controls.Remove(item);
}