无法为每个循环从数据 table 中删除行

Not able to delete row from data table on for each loop

我正在尝试根据列 match.But 从数据 table 中删除行,出现如下错误:

Collection was modified; enumeration operation might not execute

我的代码如下:

Dim dt As DataTable = CType(ViewState("SavedAccount"), DataTable)
        Dim dtTemp As DataTable = dt
        Dim count As Integer = 0
        Dim row As GridViewRow = gvAccountList.Rows(e.RowIndex)
        Dim lblAccountName As Label = CType(row.FindControl("lblAccntName"), Label)
        For Each dr As DataRow In dt.Rows


            If dr("Account_Name") = lblAccountName.Text.Trim Then


                dr.Delete()


            End If
            count = count + 1
        Next

        ViewState("SavedAccount") = dt

        AddRowInGridview()

我做错了什么?看起来很简单!

您不能在枚举时修改枚举。您可以按索引循环:

    For index = 0 To dt.Rows.Count - 1
        If dt.Rows(index)("Account_Name") = lblAccountName.Text.Trim() Then
            dt.Rows(index).Delete()
        End If
    Next
dr.Delete()

实际上并没有从数据表中删除行,而是使用,

For Each dr As DataRow In dt.Rows


        If dr("Account_Name") = lblAccountName.Text.Trim Then


            dt.Delete(dr);


        End If
        count = count + 1
    Next

我通过以下方式解决了这个问题:

  Dim dt As DataTable = CType(ViewState("SavedAccount"), DataTable)
        Dim dtTemp As DataTable = dt
        Dim count As Integer = 0
        Dim row As GridViewRow = gvAccountList.Rows(e.RowIndex)
        Dim lblAccountName As Label = CType(row.FindControl("lblAccntName"), Label)
        Dim drow As DataRow()
        drow = dt.Select("Account_Name='" + lblAccountName.Text.Trim + "'")
        For i As Integer = 0 To drow.Length - 1
            dt.Rows.Remove(drow(i))
        Next

试试这个

For i = 0 To dt.Rows.Count - 1
     'DO ....  then delete....
     dt.Rows(0).Delete()
Next