I'm trying to get the new cell value of a DataGridView
when the cell was null before. I'm using C# and this code:
private void gridViewTimes_CellLeave(object sender, DataGridViewCellEventArgs e)
{
string value = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
}
This works fine when the cell value was not null before. But if the cell was null before it throws the exception
Exception:
Object reference not set to an instance of an object
.
I'm a bit confused about this because when I leave the cell I wrote something in the cell so it isn't null anymore. Or am I understanding this wrong?
Any suggestions?
Check if the value is not null before assigning:
private void gridViewTimes_CellLeave(object sender, DataGridViewCellEventArgs e)
{
if(dataGridView1.Rows[e.RowIndex].Cells[0].Value != null)
{
string value = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
}
}
CellLeave
event is fring before value is actually changes. Use CellValueChanged
event.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.