David David - 3 months ago 37
C# Question

DataGridView cell is null on CellLeave

I am trying to do some text processing on the contents of the cell when the cell is left. I have the following code, but I get the following exception when I enter any text into the cell and then leave it.

An unhandled exception of type 'System.NullReferenceException' occurred in Program.exe

Additional information: Object reference not set to an instance of an object.


If I break and mousehover above
.value
it is indeed null, but I have entered data into the cell! So what gives?

private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 3)
{
string entry = "";
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
MakeTextFeet(entry);
}
if (e.ColumnIndex == 4)
{
string entry = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
MakeTextFeet(entry);
}
}

Answer

Add some checks:

DataGridViewCell MyCell =  dataGridView1[e.ColumnIndex, e.RowIndex];

if (MyCell != null)
{
    if (MyCell.Value != null)
    {
    }
}