how to delete row when u loop on datatable

You won't be able to do this in a For Each loop because when you remove something, the collection has changed and you can't enumerate it anymore.

What you need is a reversed For loop.

For i as Integer = Invoice.Rows.Count -1 to 0 Step -1
    Dim DrResult As Array = PaymentInvoiceDT.Select("Amount='" & Invoice.Rows(i).("Amount").ToString() & "'")
    If DrResult.Length > 0 Then
        'some code
    Else
        InvoiceDT.Rows.remove(InvoiceDT.Rows(i)) 
    End If
Next

This will still work even as you remove rows because the ones you're not touching aren't having their indexes changed and it doesn't use an enumeration.


Sai, it fails because you should not really delete the rows while looping in all table rows.

an example of what you could do, in C# is this one:

   DataTable dt = CreateDataSource();

    DataRow[] rows = (from t in dt.AsEnumerable().Cast<DataRow>()
                      where t.Field<int>("ID") == 1
                      select t).ToArray();

    foreach (DataRow row in rows)
    {
        dt.Rows.Remove(row);
    }

so as you see you first select all rows to delete with LINQ then you loop only on the resulting rows and remove them from the source table.

sorry no time to write this in VB.NET but the idea should be clear I hope.

Tags:

.Net

Vb.Net