繁体   English   中英

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

[英]NullReferenceException in string.IsNullOrWhiteSpace() and string.IsNullOrEmpty()

我正在检查可能为空或为null / null的列的单元格的单元格值,因此我需要一些避免NullReferenceException

我该怎么做,因为即使使用IsNullOrWhiteSpace()IsNullOrEmpty()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 还有什么,或者我到底在做什么错,我该怎么做正确呢?

在很多地方,您的代码都可能引发该异常..

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))

许多人不了解如何诊断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

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

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

如果value为null,则将不评估ToString(),并且程序无法引发NullReferenceException。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM