string.IsNullOrWhiteSpace()和string.IsNullOrEmpty()中的NullReferenceException

时间:2013-10-31 14:48:36

标签: c# string nullreferenceexception isnullorempty

我正在检查列的单元格的单元格值是否为空/ null所以我需要一些东西来避免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。还有什么或我到底做错了什么,我该怎么做?

4 个答案:

答案 0 :(得分:4)

你的代码很多地方都会抛出异常..

dataGridView1.Rows[0]  //here
             .Cells[0] //here
             .Value    //and here
             .ToString() 

我相信你不需要ToString()只需输入:

"... "+ dataGridView1.Rows[0].Cells[0].Value
在您的if声明中

执行此操作:

if (string.IsNullOrEmpty(dataGridView1.Rows[0].Cells[8].Value as string))

答案 1 :(得分:2)

许多人不了解如何诊断NullReferenceException。请考虑以下事项:

dataGridView1.Rows[0].Cells[3].Value.ToString()

这可能是null的很多部分。

与此相同
var a = dataGridView1.Rows;
var b = a[0];
var c = b.Cells;
var d = c[3];
var e = d.Value;
var f = e.ToString();

如果anull,则a[0]会抛出NullReferenceException。如果bnull,则b.Cells会抛出NullReferenceException等。

在您的特定情况下,您只需要确定哪些是null。最简单的方法是使用调试器。在抛出异常的行之前设置断点。然后将鼠标悬停在表达式的各个部分上以查看哪些为空,或使用“监视”窗口输入表达式的部分内容。

当您找到null时,您可以停止寻找NullReferenceException

答案 2 :(得分:0)

您可以添加额外的代码行来检查和处理空案例。

var value = dataGridView1.Rows[0].Cells[0].Value;
string s = (value == null ? string.Empty : value.ToString());

如果value为null,则不会评估ToString(),并且程序不能抛出NullReferenceException。

答案 3 :(得分:0)

我认为在dataGridView1.Rows[0].Cells[8].Value.ToString()中,如果Value为null,您将获得NullReferenceException。因此,您应该检查dataGridView1.Rows[0].Cells[8].Value != null,然后将其转换为字符串