【发布时间】:2013-11-11 15:27:33
【问题描述】:
我正在检查可能为空/空的列的单元格值,因此我需要一些东西来避免NullReferenceException。
我该怎么做,因为即使使用 IsNullOrWhiteSpace() 和 IsNullOrEmpty() 我还是会以某种方式得到该异常。
这是我正在使用的部分代码:
s = "Total = " + dataGridView1.Rows[0].Cells.Count +
"0 = " + dataGridView1.Rows[0].Cells[0].Value.ToString() +
"/n 1 = " + dataGridView1.Rows[0].Cells[1].Value.ToString() +
"/n 2= " + dataGridView1.Rows[0].Cells[2].Value.ToString() +
"/n 3 = " + dataGridView1.Rows[0].Cells[3].Value.ToString() +
"/n 4= " + dataGridView1.Rows[0].Cells[4].Value.ToString() +
"/n 5 = " + dataGridView1.Rows[0].Cells[5].Value.ToString() +
"/n 6= " + dataGridView1.Rows[0].Cells[6].Value.ToString() +
"/n 7 = " + dataGridView1.Rows[0].Cells[7].Value.ToString();
if (string.IsNullOrEmpty(dataGridView1.Rows[0].Cells[8].Value.ToString()))
{
}
else
{
s += "/n 8 = " + dataGridView1.Rows[0].Cells[8].Value.ToString();
}
我试过那些方法我试过把它==null,我试过!=null。还有什么或者我到底做错了什么,我该如何做对?
【问题讨论】:
-
我通常在这种情况下使用
as:string.IsNullOrEmpty(dataGridView1.Rows[0].Cells[8].Value as string)。如果Value不是字符串或为空,as将返回null。当然也假设这个特殊的异常是因为Value是空的。但是请注意,我的示例在语义上与尝试在某事上调用ToString不同,因为这适用于任何类型。 -
NullReferenceException的几乎所有情况都是相同的。请参阅“What is a NullReferenceException in .NET?”获取一些提示。 -
.ToString()never 返回null(在 .NET Framework 中 - 您当然可以编写一个这样做的),因此您使用.IsNullOrEmpty进行的测试对空值。事实上,您可能会通过在null的值上调用.ToString()获得异常。
标签: c# string nullreferenceexception isnullorempty