1
votes

I load a Excel worksheet when all cells are filled there´re no problems. But is a Cell empty i get a exception(its german, sorry for that):

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Die Laufzeitbindung kann für einen NULL-Verweis nicht ausgeführt werden.
bei CallSite.Target(Closure , CallSite , Object )

Ok, should be no problem, i thought, so i check the cell value if null:

for (row = 2; row <= range.Rows.Count; row++)  // Start at Row 2 to Ignore Headrow
{
    DataRow dr = dt.NewRow();
    for (column = 1; column <= range.Columns.Count; column++)
    {
        try
        {
            if(((Excel.Range)range.Cells[row, column]).Value2.ToString() != null)
            {
                dr[column - 1] = ((Excel.Range)range.Cells[row, column]).Value2.ToString();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Error " + column.ToString()); //Always Error when Cell is empty
            Console.WriteLine(e);

        }
    }

    sendConsole("Accept Row " + row + " of " + range.Rows.Count);
    dt.Rows.Add(dr);
    dt.AcceptChanges();
}

But i get still the "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException" for the null check.

1
You have to check for null before calling ToString(). You can not access properties or call methods on null. - Crowcoder
Wow! I realy thought that this time my problem isn´t a "Noob Problem" . Thank you very much!!! - Keke

1 Answers

1
votes

Value2 in your code (line 8) is null. Calling ToString on a null object will throw a null ref exception. As will calling any instance method on a null object. Do the null check on the object then call ToString on it