You need them before calling ToString . Perhaps you can even move if before adding, since I think it is not useful to add blank lines, but this might be wrong in your scenario:
if (row.Cells[i + 1, 1].Value2 != null && row.Cells[i + 1, 2].Value2 != null) { spreadsheetrows.Add(new SPREADSHEETModel.spreadsheetRow() { col1 = row.Cells[i + 1, 1].Value2.ToString(), col2 = row.Cells[i + 1, 2].Value2.ToString() }); }
Otherwise, this is probably what you need:
col1 = row.Cells[i + 1, 1].Value2 != null ? row.Cells[i + 1, 1].Value2.ToString() : null,
The reason for the exception is that Value2 is dynamic , so the return value is determined at runtime. And if Value2 is null , it cannot determine the ToString method for the call.
source share