IndexOutOfRangeException on multidimensional array

2019-07-21 05:25发布

I am using the following code to read values from an Excel spreadsheet:

// Start with passed
int lastPassRow = sheets[passedVehicles].GetLength(0);

for (int i = 1; i < lastPassRow; i++)
{
   // Exception here
   if(DateTime.TryParse(sheets[passedVehicles][i, 0].ToString(), out result))
   {
      passedDates.Add((DateTime)sheets[passedVehicles][i, 0]);
   }
}

The type of sheets[passedVehicles] is a multidimensional array of Object[,] and the for loop above is giving me an IndexOutOfRange exception at i = 1, despite that I check the number of rows.

I added some logging for the spreadsheet in question, and have verified:

  • i = 1 is the iteration that is failing
  • The value of lastPassRow is 4
  • The value of sheets[passedVehicles].GetLength(1) is also four.

All values appear to be in range to me. Is there something else that could cause this exception?

Note: I am starting at i = 1 because row 0 is a header in the spreadsheet and does not contain data I am trying to read.

1条回答
走好不送
2楼-- · 2019-07-21 06:17

I suspect it's the 0 that's out of range.

Excel arrays are 1-based, not 0-based as you might expect.

查看更多
登录 后发表回答