无法对空引用exception执行运行时绑定

我试图通过查找第一列(由date组成)和标题行中的第一个空单元格来使用C#查找Excel表格的维度。

这里是我现在使用的代码:

public static void findingTableBounds() { string dateCol = ""; ArrayList dateColumn = new ArrayList(); ArrayList numberOfColumns = new ArrayList(); for (int column = 1; column < currentRow; column++) { dateCol = ((Excel.Range)workSheet.Cells[currentRow, 1]).Value2.ToString(); if (dateCol != "") { dateColumn.Add(dateCol); currentRow++; totalRow++; Console.WriteLine("Total Row: {0}", totalRow); } else { Console.WriteLine("Total Row: {0}", totalRow); currentRow = 2; } } 

**注意:这个方法有一个右括号,我没有包含它,因为还有另外一个for循环,和上面的代码完全一样,但是只有多less列。

该错误发生在“dateCol =((Excel.Range)workSheet.Cells [currentRow,1])。Value2.ToString();” 我敢肯定,这是因为我试图分配一个空值(单元格)dateCol(一个string),当string是一个非空types。 不幸的是我不知道如何解决这个问题。

如果((Excel.Range)workSheet.Cells[currentRow, 1]).Value2为null,那么它没有一个函数ToString执行它不起作用。 它是否说什么types的exception呢? 因为可能会有更大的问题

关于上面的post(我没有足够的评价来评论)

为了帮助其他失去的灵魂,我提高了这个职位,只是补充说:

if(((Excel.Range)workSheet.Cells [currentRow,1])。Value2!= null){…}。
– Sylvain 15年2月16日在21:07

我有一个问题,并用它,但发现,至less在我的情况下,我改变了这个:

 if (excelWorksheet.Cells[row, column].Value2 != null) { return ((Excel.Range)excelWorksheet.Cells[row, column]).Value2.ToString(); } return "No data"; 

至less在我的特定情况下工作。 在创build错误中具有Excel.Range部分。