C# 变量始终在datagridview中存储空值

C# 变量始终在datagridview中存储空值,c#,variables,datagridview,cell,C#,Variables,Datagridview,Cell,我想存储DataGridView控件的单元格值,但无论单元格是否包含值,此变量始终存储空值 var cellValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; 如果我这样做: string cellValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() ; 它会产生以下错误: 未处理NullReferenceEx

我想存储DataGridView控件的单元格值,但无论单元格是否包含值,此变量始终存储空值

var cellValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
如果我这样做:

string cellValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() ; 
它会产生以下错误:

未处理NullReferenceException


我在诸如CellEndEdit、CellValidating、CellLeave等各种事件中使用了它,但结果是一样的。我应该如何在单元格中保存正确的值,包括null,即如果任何单元格为空。

发生错误是因为您调用的是null对象上的字符串。解决方案是首先测试它是否为null,然后在它为null时执行不同的操作:

编写此逻辑的较短方法是:

string cellValue = (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null)
    : string.Empty // or null, depending on how you want to store null values
    ? dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
string cellValue = (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null)
    : string.Empty // or null, depending on how you want to store null values
    ? dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();