删除 TextBox ,位置问题 C#

Removing TextBox , Location issue C#

我想在 trackbar_scroll 上动态创建文本框。如果 trackbar 的值为 5,则它可能有 5 个文本框。当它减少到 2 时,它必须有 2 个文本框。这是我减少 trackbar_scroll 值时的问题:

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

您无法在列表上逐个修改列表,但如果您使用列表的副本则可以:

foreach (TextBox tb in this.Controls.OfType<TextBox>().ToList()) {
  tb.Dispose();
}

您正在尝试修改 this.Controls,同时通过 foreach 对其进行迭代。现在允许这样做,因为它会导致簿记问题。要修复您的错误,请使用从末尾开始的 for 循环向后遍历列表,或者使用临时列表来存储您打算删除的控件,然后遍历该列表以实际删除它们。