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

Mic*_*cio 0 c# string nullreferenceexception isnullorempty

我正在检查可能为空/空/空的列的单元格的单元格值,所以我需要一些东西来避免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();
    }
Run Code Online (Sandbox Code Playgroud)

我试过那些我试过的方法==null,我试过!=null。还有什么或者我做错了什么,我该怎么做?

Jen*_*ter 5

您编码的很多地方都可能抛出该异常..

dataGridView1.Rows[0]  //here
             .Cells[0] //here
             .Value    //and here
             .ToString() 
Run Code Online (Sandbox Code Playgroud)

我相信你不需要ToString()just 类型:

"... "+ dataGridView1.Rows[0].Cells[0].Value
Run Code Online (Sandbox Code Playgroud)

在你的 if声明中这样做:

if (string.IsNullOrEmpty(dataGridView1.Rows[0].Cells[8].Value as string))
Run Code Online (Sandbox Code Playgroud)