Ubaid Ashraf
Ubaid Ashraf

Reputation: 885

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

I am trying to delete row from data table based on column match.But getting error as follows :

Collection was modified; enumeration operation might not execute

My code is as :

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()

What am I doing wrong? It seems pretty simple!

Upvotes: 1

Views: 3731

Answers (4)

Jorge Rocha
Jorge Rocha

Reputation: 788

Try this

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

Upvotes: 0

Ubaid Ashraf
Ubaid Ashraf

Reputation: 885

I solved this problem by doing as below:

  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

Upvotes: 0

Insane
Insane

Reputation: 664

dr.Delete()

Does not actually delete the row from the DataTable, Instead use,

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

Upvotes: 0

Crowcoder
Crowcoder

Reputation: 11514

You cannot modify an enumeration while you are enumerating it. You can loop by index instead:

    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

Upvotes: 2

Related Questions