【发布时间】:2012-09-19 15:21:10
【问题描述】:
我有以下代码可以将先前的值输入到 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;
}
只要有值得查看和复制的价值,它就很有效。但是,如果单元格为空白,我会得到:
System.NullReferenceException 未被用户代码处理
Message=对象引用未设置为对象的实例。
我猜这是一个使用空合并运算符的机会,但是(假设我的猜测不错),我该如何实现呢?
【问题讨论】:
标签: c# winforms datagridview nullreferenceexception datagridviewtextboxcell