【发布时间】:2017-12-31 12:14:06
【问题描述】:
当所有单元格都填满时,我会加载 Excel 工作表,没有问题。 但是一个单元格是空的,我得到了一个例外(它的德语,对此感到抱歉):
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:死 Laufzeitbindung kann für einen NULL-Verweis nicht ausgeführt werden.
bei CallSite.Target(Closure , CallSite , Object )
好的,我想应该没问题,所以我检查单元格值是否为空:
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();
}
但我仍然得到“Microsoft.CSharp.RuntimeBinder.RuntimeBinderException”进行空检查。
【问题讨论】:
-
您必须在调用 ToString() 之前检查 null。您无法访问 null 上的属性或调用方法。
-
哇!我真的认为这次我的问题不是“菜鸟问题”。非常感谢!!!