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: