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