When refreshing my DGV contents (not data-bound, populated in code), I've got this code that retrieves the values in the cells:
DataGridViewRow desiredRow = dataGridViewPlatypi.Rows[rowNum];
return desiredRow.Cells[colNum].Value.ToString();
It works fine as long as there is a value in the cell; if the cell is empty, it fails with " Null reference exception | Object reference not set to an instance of an object " on the second line.
I can work around this my giving each cell a "0" or a " " (space), but I'd rather not do that. Is there a more elegant way of handling this (blank cell) condition?
You can use the null-coalescing operator to test for a null value in your cell and if the value is found to be null, return a string of your choice. Otherwise the cell's string value is returned:
DataGridViewRow desiredRow = dataGridViewPlatypi.Rows[rowNum];
return (desiredRow.Cells[colNum].Value ?? "empty").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.