如何在有机会抛出异常之前将null值转换为string.empty?

B. *_*non 1 c# datagridview nullreferenceexception winforms datagridviewtextboxcell

我有以下代码将以前的值输入DataGridView单元格.如果在第0行和第2列或更大,则向左的val,否则直接在上面的值:

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;
}
Run Code Online (Sandbox Code Playgroud)

只要有值可以查看和复制,这就很有用.如果单元格是空白的,我得到:

用户代码未处理System.NullReferenceException
消息=未将对象引用设置为对象的实例.

我猜这是一个使用null coalesce运算符的机会,但(假设我的猜测很好),我该如何实现呢?

Nic*_*rey 5

尝试这样的事情:

string s = SomeStringExpressionWhichMightBeNull() ?? "" ;
Run Code Online (Sandbox Code Playgroud)

简单!