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, 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 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 ne开发者_如何学Pythonxt 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?
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?
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 .
Looking for slow performance in an application I found that try/catch is one of the most expensive operations you can do. In my test, sometime ago, it was taking 250 mSec. Since then I never use a try catch except as a final safeguard against errors I never thought of. Even then I arrange for an error to be logged so that the particular error can be recognized and handled directly.
精彩评论