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);
}
}
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.
Add some checks:
DataGridViewCell MyCell = dataGridView1[e.ColumnIndex, e.RowIndex];
if (MyCell != null)
{
if (MyCell.Value != null)
{
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With