For Each Loop 错误:集合已修改;枚举操作可能无法执行
我在循环数据行时遇到错误。我搜索了SO并尝试了解决方案,但没有运气。
集合已修改;枚举操作可能无法执行。
Dim dRow As DataRow
For Each dRow In dt.Rows
dt.Rows.Add(dRow("CustNum"), dRow("SalesRepName"), dRow("mgrid"), "=""" & dRow("midValue") & """", dRow("dba"), dRow("sysDate"), dRow("statusID"))
Next
代码第一次点击“Next
”时会发生错误
导致 Collection 的原因被修改;枚举操作可能无法执行。如何解决此错误?
I am encountering an error when looping through datarows. I searched SO and tried the solutions, but no luck.
Collection was modified; enumeration operation might not execute.
Dim dRow As DataRow
For Each dRow In dt.Rows
dt.Rows.Add(dRow("CustNum"), dRow("SalesRepName"), dRow("mgrid"), "=""" & dRow("midValue") & """", dRow("dba"), dRow("sysDate"), dRow("statusID"))
Next
The error occurs the first time the code hits "Next
"
What would be causing Collection was modified; enumeration operation might not execute.How can I resolve this error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更新集合时无法枚举集合。即使这段代码确实有效,它也会永远运行,因为您不断添加越来越多的行,并且它会不断枚举它们。
您可以稍微改变您的方法,并通过使用带有索引计数器和固定上限的 for 循环来实现此目的。
像这样的东西应该有效:
You cannot enumerate a collection while updating it. Even if this code actually did work, it would run forever because you keep adding more and more rows and it would keep enumerating them.
You can change your approach slightly and make this work by using a for loop with an index counter and a fixed upper bound.
Something like this should work:
您正在将项目添加到您正在枚举的集合中。从逻辑上讲,它会无限循环。这种情况是不可能出现的。如果您确实打算这样做,请通过为数据创建
Structure
或Class
将其分成两部分,将项目添加到列表中,然后循环列表并添加将物品放到桌子上。You're adding items to a collection you're enumerating. Logically, it would loop infinitely. This sort of situation can't occur. If you really mean to do that, split it in two by creating a
Structure
orClass
for your data, adding the items to a list, then looping through the list and adding the items to the table.