1

I have the following code to enter a previous value into a DataGridView cell. If on row 0 and col 2 or greater, the val to the left, otherwise the value directly above:

private void dataGridViewPlatypi_CellEnter(object sender, DataGridViewCellEventArgs args)
{
    // TODO: Fails if it sees nothing in the previous cell
    string prevVal = string.Empty;
    if (args.RowIndex > 0)
    {
        prevVal = dataGridViewPlatypi.Rows[args.RowIndex - 1].Cells[args.ColumnIndex].Value.ToString();
    } else if (args.ColumnIndex > 1)
    {
        prevVal = dataGridViewPlatypi.Rows[args.RowIndex].Cells[args.ColumnIndex-1].Value.ToString();
    }
    dataGridViewPlatypi.Rows[args.RowIndex].Cells[args.ColumnIndex].Value = prevVal;
}

This works great as long as there is a value to be seen and copied over. If the cell is blank, though, I get:

System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.

I'm guessing this is an opportunity to use the null coalesce operator, but (assuming my guess is good), just how do I implement that?

3 Answers 3

5

Try something like this:

string s = SomeStringExpressionWhichMightBeNull() ?? "" ;

Easy!

1
3

Assuming Value is what is null (not entirely clear from your post) you can do

object cellValue = 
    dataGridViewPlatypi.Rows[args.RowIndex - 1].Cells[args.ColumnIndex].Value;
prevValue = cellValue == null ? string.Empty : cellValue.ToString()
1
  • The second line can be written: prevValue = cellValue?.ToString() ?? string.Empty
    – pensono
    Oct 8, 2019 at 6:11
3

Use a method such as:

public static class MyExtensions
{
    public static string SafeToString(this object obj)
    {
        return (obj ?? "").ToString();
    }
}

then you can use it like:

object obj = null;

string str = obj.SafeToString();

or as an example from your code:

prevVal = dataGridViewPlatypi.Rows[args.RowIndex - 1].Cells[args.ColumnIndex].Value.SafeToString();

This creates an extension method, so if you add a using for the namespace that the extensions class is in all objects will appear to have a SafeToString method in intellisense. The method isn't actually an instance method, it just appears as one, so instead of generating a null reference exception if the object is null it simply passes null to the method, which treats all null values as empty strings.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.