IndexOutOfRangeException on multidimensional array despite using GetLength check

纵饮孤独 提交于 2019-12-24 03:46:06

问题


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:


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

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



来源:https://stackoverflow.com/questions/30327476/indexoutofrangeexception-on-multidimensional-array-despite-using-getlength-check

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!