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.
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();
}
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?
asin this situation:string.IsNullOrEmpty(dataGridView1.Rows[0].Cells[8].Value as string).aswill returnnullifValueis not a string or is null. Also assuming of course that this particular exception is becauseValueis null. Do note, however, that my example is semantically different from attempting to callToStringon something, as that will work for any type.NullReferenceExceptionare the same. Please see "What is a NullReferenceException in .NET?" for some hints..ToString()never returnsnull(in the .NET Framework - you could of course write one that does), so your test with.IsNullOrEmptyis pointless against null. In fact, you probably get the exception from calling.ToString()on a value that isnull.