I'm trying to validate the content of a cell inside a DataGridView when the CellValidated event is fired and I've seen different ways to deal with the problem, but I can't get around the Null error when running the application.
The error I get is NullReferenceException was Unhandled
and that the reference is not set to an instance of an object. This error happens when I leave the cell blank to move to another cell, that If
's when it drops. It should be noted that I am using the Grid
for a direct entry.
What I'm thinking of including is a try..catch
to bypass the problem, but I think that's not the best option.
The code of the event that I am using is the following:
private void dgvProductosPropios_CellValidated(object sender, DataGridViewCellEventArgs e)
{
if (dgvProductosPropios.Columns[e.ColumnIndex].Name == "_marcaCodigo")
{
if (dgvProductosPropios.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == String.Empty)
cMarca = dgvProductosPropios.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
else
cMarca = "";
}
}
Try validating the cell first: