Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
基本上我所做的是:通过单击按钮添加(n)文本框。当我再次单击它时,此代码运行:
foreach (Control c in this.Controls) { TextBox tb = c as TextBox; if (tb != null) { this.Controls.Remove(tb); tb.Dispose(); } }
我再次添加(n)个文本框,但旧文本框中的每隔一个项目都会保留。有任何想法吗?
从您正在迭代的集合中删除项目是一个坏主意。尝试这个:
List<Control> toBeRemoved = new List<Control>(); foreach (Control c in this.Controls) { if (c instanceof TextBox) { toBeRemoved.Add(c); } } foreach (Control c in toBeRemoved) { this.Controls.Remove(c); c.Dispose(); }