我试图根据列匹配从数据表中删除行。但是得到如下错误:
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()
我做错了什么?看起来很简单!
答案 0 :(得分:2)
在枚举枚举时,无法修改枚举。您可以通过索引循环:
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
答案 1 :(得分:0)
dr.Delete()
实际上并没有从DataTable中删除该行,而是使用
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
答案 2 :(得分:0)
我通过以下方式解决了这个问题:
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
答案 3 :(得分:0)
尝试一下
For i = 0 To dt.Rows.Count - 1
'DO .... then delete....
dt.Rows(0).Delete()
Next