views:

211

answers:

3

Why does the code below result in 3 rows in my datagrid when there is only 2 rows in my CSV file? I end up with 2 populated rows and one empty row. The CSV file only contains 2 lines. I suspect the logic of the code below.

Do While Read()
    row = New DataGridViewRow()
    For Index = 0 To FieldCount - 1
        cell = New DataGridViewTextBoxCell()
        cell.Value = GetString(Index).ToString()
        row.Cells.Add(cell)
    Next
    DataView.Rows.Add(row)
Loop

Thanks

A: 

Do you have an extra newline at the end of your csv file?

codefly
A: 

Do you have a trailing end-of-line at the end of the last line? If so then the code will be seeing the file as two full lines and one empty one.

If you know you will always have a final separator (line break in this case) then simply take an extra 1 off then ending value of the for loop. Otherwise check the last line first (to see if you need to loop once less) or check each line within the loop (this will be far less efficient).

David Spillett
+2  A: 

If you have the AllowUserToAddRows property of the datagridview set to true, an extra row with a "*" will appear for that purpose.

David
This is the most likely solution, the last row will have the IsNewRow property set to True
Patrick McDonald