Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
}
like image 390
David Avatar asked Nov 13 '12 02:11

David


2 Answers

The value of a cell is in a transient state when the DataGridView CellLeave event fires. This is because DataGridView may be bound to a datasource and the change will not have been commited.

Your best option is to use the CellValueChanged event.

like image 59
pgfearo Avatar answered Oct 14 '22 11:10

pgfearo


Add some checks:

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

if (MyCell != null)
{
    if (MyCell.Value != null)
    {
    }
}
like image 1
Steve Wellens Avatar answered Oct 14 '22 10:10

Steve Wellens