I want to loop through the cells when the customer passes it back to me. I may have a different number of cells depending on the query execution, so I want to loop from the first cell to however many cells I have:
Dim Str As String, cellCount As IntegerStr = "Hello: " cellCount = CInt(e.Row.Cells.Count)For i As Integer = 1 To cellCount Step 1 Str = Str & e.Row.Cells(i).Text 'Error Thrown Here: Object reference not set to an instance of an objectNext
If I swap out the i in the cell count with an actual number, it works just fine:Str = Str & e.Row.Cells(2).Text
If I just print out the loop control variable i, it prints numbers you would expect. I have no idea why it is throwing this error.
TIA.
The cells collection is a zero-based collection, but your loop suggests that it's one-based. So, in the last iteration of your loop, you're looking for a cell that isn't there - for instance, if you have 5 columns (and thus 5 cells), the call to e.Row.Cells(5) fails because this would be the sixth cell in the row.
Try adjusting your loop as follows:
For i As Integer = 0 To (cellCount-1) Step 1
Thank you, I should have thought of that.