【问题标题】:Removing TextBox , Location issue C#删除 TextBox ,位置问题 C#
【发布时间】:2016-05-18 17:41:37
【问题描述】:

我想在 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;
        }
    }

【问题讨论】:

    标签: c# dynamic textbox trackbar


    【解决方案1】:

    您不能像 for-each 一样修改列表,但如果您使用列表的副本,则可以:

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

    【讨论】:

    • 谢谢,它有效。请您详细说明一下。 foreach(this.Controls 中的 control ctrl)和您的代码有什么区别。
    • @A.RShaib 真正的区别在于ToList() 会生成列表的副本。在您的原始代码中,从集合中删除一个控件会更改集合,因此下一个控件会关闭一个,等等。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多