简体   繁体   中英

Check if datagridview value is not null when changing cell

I'm using a CellEndEdit Event for capturing currentCell Value when I'm leaving from it. The problem is that, if the user deletes all the cell and trying to move to another cell I'm getting error Exception thrown System.NullReference .

Here is my code which I tell that if the cell is null or empty do nothing

I tried:

 if ( AppointmentGrid[e.ColumnIndex, e.RowIndex].Value != "")
 if ( AppointmentGrid[e.ColumnIndex, e.RowIndex].Value != null)
 if ( AppointmentGrid[e.ColumnIndex, e.RowIndex].Value.ToString() != "")
 if ( AppointmentGrid[e.ColumnIndex, e.RowIndex].Value.ToString() != "")
 if ( !String.IsNullOrWhiteSpace(AppointmentGrid[e.ColumnIndex, e.RowIndex].Value.ToString()))

Nothing from above doesn't work I get the Null reference . Is there any other to check if my current cell doesn't have something inside?

Perhaps Value is null. You can use the null propagation operator ? to avoid the exception.

 if ( AppointmentGrid[e.ColumnIndex, e.RowIndex]?.Value != "")
 if ( AppointmentGrid[e.ColumnIndex, e.RowIndex]?.Value != null)
 if ( AppointmentGrid[e.ColumnIndex, e.RowIndex]?.Value.ToString() != "")
 if ( AppointmentGrid[e.ColumnIndex, e.RowIndex]?.Value.ToString() != "")
 if ( !String.IsNullOrWhiteSpace(AppointmentGrid[e.ColumnIndex, e.RowIndex]?.Value.ToString()))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM