Many people don't understand how to diagnose a NullReferenceException
. Consider the following:
dataGridView1.Rows[0].Cells[3].Value.ToString()
Many parts of this could be null
. It's the same thing as
var a = dataGridView1.Rows;
var b = a[0];
var c = b.Cells;
var d = c[3];
var e = d.Value;
var f = e.ToString();
If a
is null
, then a[0]
will throw a NullReferenceException
. If b
is null
, then b.Cells
will throw a NullReferenceException
, etc.
You simply have to figure out which of these is null
in your particular situation. The simplest way is to use the debugger. Set a breakpoint before the line that throws the exception. Then hover the mouse over various parts of the expression to see which are null, or use the "Watch" window to enter parts of the expression.
When you find a null
, you can stop looking for your NullReferenceException
.