Removing rows from datatable + AcceptChanges

I have 2 datatables in my ASP.NET application. I am looping though they are both, and if I find a match, I remove that particular row from the outer datatable, like 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 great except when dtFixedActs only contains 1 row and the match is found in another datatable. I am getting the error "no row at position 1". This makes sense because with i + = 1 I want to go to the next line, which is not possible in this case.

I have tried moving the dtFixedActs.AcceptChanges command to and from the 1st loop, to no avail. I also commented out the line i + = 1, but then I get the message "The deleted line could not be accessed via the line." mistake.

I don't know how to program this problem. When dtFixedActs contains more than 1 line, no problem occurs.

Any suggestions?

+2


source to share


3 answers


The strangest thing seems to be I solved the problem. I have added a block of code for the exception catch exception 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 is working fine now. Does anyone have an explanation for this as I doubt this is a valid solution?

+2


source


you have a problem if a match is found dfFixedActs (dtFixedActs.Count - 1) because I am incrementing to the border. just added a condition to prevent i or j from going out of bounds, for example i <= dtFixedActs.Count - 1 and j <= dtTotals.Count - 1.



0


source


While looking for slow performance in my application, I found try / catch to be one of the most expensive operations you can do. In my test, at one time, it took 250ms. Since then, I never use try catch, except as the ultimate protection against errors that I never thought of. Even then, I organize the error log so that the specific error can be recognized and handled directly.

0


source







All Articles