string.IsNullOrWhiteSpace() 和 string.IsNullOrEmpty() 中的 NullReferenceException [英] NullReferenceException in string.IsNullOrWhiteSpace() and string.IsNullOrEmpty()
问题描述
我正在检查可能为空/空/空的列的单元格值,所以我需要一些东西来避免 NullReferenceException
.
I'm checking the cell values of cells of a column that might or not be empty/null so I needed something to avoid a NullReferenceException
.
我该怎么做,因为即使使用 IsNullOrWhiteSpace()
和 IsNullOrEmpty()
我也会以某种方式得到该异常.
How do I do that since even with the IsNullOrWhiteSpace()
and IsNullOrEmpty()
I get that exception somehow.
这是我正在使用的代码的一部分:
Here's part of the code I'm using:
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
.还有什么或者我做错了什么,我该怎么做?
I've tried those methods I've tried putting it ==null
, I've tried !=null
. What else is there or what am I doing wrong exactly and how do I do it right?
推荐答案
您的代码可能会在很多地方抛出该异常..
the are a lot of places you code could throw that exception ..
dataGridView1.Rows[0] //here
.Cells[0] //here
.Value //and here
.ToString()
我相信您不需要 ToString()
只需输入:
I belive you don't need the ToString()
just type:
"... "+ dataGridView1.Rows[0].Cells[0].Value
在您的 if
语句中执行以下操作:
in your if
statement do this:
if (string.IsNullOrEmpty(dataGridView1.Rows[0].Cells[8].Value as string))
这篇关于string.IsNullOrWhiteSpace() 和 string.IsNullOrEmpty() 中的 NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!