Stopbyte

DataGridView Exception: "Object reference not set to an instance of an object."

I am encountering an exception :

“Object reference not set to an instance of an object.”

in this C# Code:

string description = "";
string cell0 = "";
string cell1 = "";
 
for (int i = 1; i <= DataGridView1.Rows.Count; i++)
{
    part1 = DataGridView1.Rows[i].Cells[0].Value.ToString();
    part2 = DataGridView1.Rows[i].Cells[1].Value.ToString();
    description += cell0 + " => " + cell1 + "\r\n";
}
 
MessageBox.Show("Description is: " + description);

The exception occurs at line 7.

part1 = DataGridView1.Rows[i].Cells[0].Value.ToString();

Can you please help me?

2 Likes

a DataGridView Cell.Value property can be null, so before calling .ToString() you should check it is not null first:

example:

part1 = DataGridView1.Rows[i].Cells[0].Value != null ? 
            DataGridView1.Rows[i].Cells[0].Value.ToString() : "";

that should do the trick.

1 Like