-2
            Dim CurrentRow As DataRow
            Dim NextRow As DataRow

            For i = 0 To dt.Rows.Count - 1
                'checks if taskid matches row id. if so then enter condition
                If dt.Rows(i)("TaskID") = RowID Then
                    'needs to check if next row exist. if it does then get the next row . if not (hence its the final row get it)
                    If dt.Rows(i + 1) Is Nothing Then
                        CurrentRow = dt.Rows(i)
                    Else
                        NextRow = dt.Rows(i + 1)
                    End If


                    Exit For
                End If
            Next

I've literally swiped the internet and yet cannot find a valid solution. I'm looping through this datatable and I'm retrieving the next row. But always no matter what i do a point will come where the dt.rows(i+1) will no longer proceed as it cannot find any rows in that position. One thing i don't understand is that if dt.rows(i+1) comes back empty or does not exist as the error suggests then you could do a simple if condition to check if its nothing. But I get this enter image description here

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Goku1989
  • 1
  • 1
  • You guess wrong. I'd rather know that I was making a mistake and avoid making it in future. Maybe you'd rather blissful ignorance. You're free to ignore any comments you find too challenging. – jmcilhinney May 11 '18 at 07:34

1 Answers1

2

Think it through. What does this code do:

For i = 0 To dt.Rows.Count - 1

It loops from the index of the first row to the index of the last row. If your intention in the loop is to compare the row at the current index to the row at the next index, how can it possibly make sense to loop to the last row? There is no row after the last row so why would you loop to the last row? You need to loop to the last row that has a row after it. It should be obvious that that is the second-last row. Fix your broken loop:

For i = 0 To dt.Rows.Count - 2
jmcilhinney
  • 50,448
  • 5
  • 26
  • 46