0

Below is the code . Here i am adding 2 textboxes and a button dynamically on button click. Am tagging the textboxes to dynamically created button(remove). So on click of remove button i need to remove the textboxes tagged to it. But only 1 textbox is getting removed and not the other. Am not able to find out the reason for tat.

   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);
 }
}
Robin
  • 87
  • 3
  • 14
  • Please, do not include information about a language used in a question title unless it wouldn't make sense without it. Tags serve this purpose. – Ondrej Janacek Feb 27 '14 at 07:00

1 Answers1

0

When deleting items from a list, instead of using a foreach, try using a for, and iterate backwards. The following question has some solutions that are similar in nature to this one:

Safely Removing DataRow In ForEach

So, something like this (I haven't tested this code, but this is the general idea):

// 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);
}
Community
  • 1
  • 1
CJBS
  • 15,147
  • 6
  • 86
  • 135