For Each Loop 错误:集合已修改;枚举操作可能无法执行

发布于 2024-12-10 12:37:49 字数 424 浏览 0 评论 0原文

我在循环数据行时遇到错误。我搜索了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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

薄凉少年不暖心 2024-12-17 12:37:49

更新集合时无法枚举集合。即使这段代码确实有效,它也会永远运行,因为您不断添加越来越多的行,并且它会不断枚举它们。

您可以稍微改变您的方法,并通过使用带有索引计数器和固定上限的 for 循环来实现此目的。

像这样的东西应该有效:

Dim rowCount As Integer = dt.Rows.Count  ' Set upper bound = original row count
Dim index as Integer
For index = 0 To rowCount - 1  ' Iterate through the original set of rows
    Dim dRow as DataRow = dt.Rows.Item(index)  ' Get row by index
    dt.Rows.Add(dRow("CustNum"), dRow("SalesRepName"), dRow("mgrid"), "=""" & dRow("midValue") & """", dRow("dba"), dRow("sysDate"), dRow("statusID"))
Next index

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:

Dim rowCount As Integer = dt.Rows.Count  ' Set upper bound = original row count
Dim index as Integer
For index = 0 To rowCount - 1  ' Iterate through the original set of rows
    Dim dRow as DataRow = dt.Rows.Item(index)  ' Get row by index
    dt.Rows.Add(dRow("CustNum"), dRow("SalesRepName"), dRow("mgrid"), "=""" & dRow("midValue") & """", dRow("dba"), dRow("sysDate"), dRow("statusID"))
Next index
往事随风而去 2024-12-17 12:37:49

您正在将项目添加到您正在枚举的集合中。从逻辑上讲,它会无限循环。这种情况是不可能出现的。如果您确实打算这样做,请通过为数据创建 StructureClass 将其分成两部分,将项目添加到列表中,然后循环列表并添加将物品放到桌子上。

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 or Class for your data, adding the items to a list, then looping through the list and adding the items to the table.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文