views:

423

answers:

2

Hi everybody,

I have 2 datatables in my ASP.NET application. I loop though both of them, and if I find a match, I delete that particular row from the outer datatable, lik so:

For i As Integer = 0 To dtFixedActs.Count - 1
        For j As Integer = 0 To dtTotals.Count - 1                
            If dtFixedActs.Rows(i).Item("Activity") = dtTotals.Rows(j).Item("Activity") Then
                dtFixedActs.Rows(i).Delete()
                i += 1
                j += 1
            End If
        Next            
        dtFixedActs.AcceptChanges()
    Next

This works fine, except when the dtFixedActs contains only 1 row and a match is found in the other datatable. I get an "there is no row at position 1" error. This makes sense because with i+=1 I want to get to the next row, which is not possible in this case.

I have tried to move around the dtFixedActs.AcceptChanges command in and out of the 1st loop but to no avail. I also commented out the i+=1 line, but then I get the "Deleted row information cannot be accessed through the row." error.

I don't know how to program around this issue. When dtFixedActs contains more than 1 row, the problem does not occur.

Any suggestions? Thanks in advance!

A: 

you will have a problem if a match is found dfFixedActs(dtFixedActs.Count - 1), because i increase to out side boundary. just added a condition to prevent i or j move out of the boundary, such as i <= dtFixedActs.Count - 1 and j <= dtTotals.Count - 1 .

Henry Gao
Thanks Henry, I already tried this, but then I get the "Deleted row information cannot be accessed through the row." error.
Stijn Van Loo
you need to test it again, before the second next. may be another variable x to keep track of how many rows you have deleted. you i can not loop to dtFixedActs.Count - 1, you can just loop to dtFixedActs.Count - 1 - x.
Henry Gao
you try catch will work, but you should handle the exception. another point is you should not leave the code open for the obvious known exception
Henry Gao
Thanks for your help Henry!
Stijn Van Loo
+1  A: 

Strangest thing, I seem to have solved the issue. I added a try catch exception code block like so:

For i As Integer = 0 To dtFixedActs.Count - 1
        For j As Integer = 0 To dtTotals.Count - 1                
            Try
                If dtFixedActs.Rows(i).Item("Activity") = dtTotals.Rows(j).Item("Activity") Then
                    dtFixedActs.Rows(i).Delete()
                    i += 1
                    j += 1
                End If
            Catch ex As Exception

            End Try

        Next
        dtFixedActs.AcceptChanges()
    Next

Everything seems to work fine now. Does anyone have an explanation for this, as I doubt that this is a valid solution?

Stijn Van Loo