1

I want to create textboxes dynamically on trackbar_scroll. If trackbar has a value of 5, it may have 5 textboxes. When it decreases to 2, it must have 2 textboxes. Here is the problem when I decrease trackbar_scroll value:

private void trackBar1_Scroll(object sender, EventArgs e)
    {
        foreach (Control ctrl in this.Controls) // to remove all textboxes before creating new
        {
            if (ctrl is TextBox)
            {
                this.Controls.Remove(ctrl);
                ctrl.Dispose();
            }
        }

        int x = 45; // location for textbox

        for (int i = 0; i < trackBar1.Value; i++)
        {
            listBox1.Items.Add(i);
            TextBox _text = new TextBox();
            _text.Name = "txt"+i;
            _text.Height = 20;
            _text.Width = 100;
            _text.Text = _text.Name;

            _text.Location = new Point(x, 85);
            this.Controls.Add(_text);
            x = x + 120;
        }
    }
Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
Allah Rakha
  • 65
  • 2
  • 11

2 Answers2

1

You can't modify the list as you for-each over it, but you can if you use a copy of the list:

foreach (TextBox tb in this.Controls.OfType<TextBox>().ToList()) {
  tb.Dispose();
}
LarsTech
  • 80,625
  • 14
  • 153
  • 225
  • thanks , it works. Would you like to elaborate please. What is difference between foreach ( control ctrl in this.Controls) and your code. – Allah Rakha May 18 '16 at 17:55
  • @A.RShaib The real difference is the `ToList()` which makes a copy of the list. In your original code, removing a control from the collection changes the collection, so the next control is off by one, etc. – LarsTech May 18 '16 at 18:00
0

You're trying to modify this.Controls while iterating over it via foreach. This is now allowed, as it causes bookkeeping problems. To fix your bug, either iterate backwards through the list with a for loop that starts at the end, or use a temporary list to store controls you intend to remove and then iterate over that list to actually remove them.

adv12
  • 8,443
  • 2
  • 24
  • 48