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

Jes*_*mon 7 c# excel exception

我试图通过查找第一列(由日期组成)和标题行中的第一个空单元格来使用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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

**注意:此方法有一个结束括号,我没有包含它,因为还有另一个for循环与上面的代码完全相同但只有多少列.

错误发生在"dateCol =((Excel.Range)workSheet.Cells [currentRow,1]).Value2.ToString();" 我很确定它会发生,因为我正在尝试在string为非可空类型时将null值(单元格)分配给dateCol(字符串).不幸的是我不确定如何解决这个问题.

inv*_*bob 9

将null值应用于字符串是可行的,但如果 ((Excel.Range)workSheet.Cells[currentRow, 1]).Value2为null,则它没有函数ToString()不是函数,因此尝试执行它不起作用.它说它是什么类型的例外?因为可能会有更大的问题......