0

I want to store the cell value of the DataGridView control, but this variable is always storing null values, whether or not the cell contains a value.

var cellValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

If I do the following:

string cellValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() ; 

it produces the error:

NullRefrenceException was unhandled .

I used it in various events like CellEndEdit, CellValidating, CellLeave, but the result is the same. What should I do to save the correct value in hte cell including null also (ie. if any cell is empty).

Rufus L
  • 32,853
  • 5
  • 25
  • 38
speedyraz
  • 305
  • 3
  • 16

1 Answers1

1

The error is happening because you're calling ToString() on a null object. The solution is to test it for null first, and then do something different if it's null:

var actualCellValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

// Choose a default value in case it's null (string.Empty or null)
string cellValue = string.Empty; 

// Test the value for null, and if it isn't, call ToString() on it
if (actualCellValue != null) cellValue = actualCellValue.ToString();

A shorter way to write this logic is:

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();
Rufus L
  • 32,853
  • 5
  • 25
  • 38