Question

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?

Était-ce utile?

La solution

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()

Autres conseils

Try something like this:

string s = SomeStringExpressionWhichMightBeNull() ?? "" ;

Easy!

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top