Why is the DataGridViewRow.Cells[x].Value returns null while it is not null?

248 Views Asked by At

I know it seems a duplicate of this question, but I have something different to ask. I am working on a simple winforms project which connects with a local database file which has two tables. I am showing data from those tables in two different datagridviews in two forms. Also I am changing colors of the rows of datagridview to differentiate male and female.

on one form the below code works and change color of the row.

foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Cells[4].Value.ToString().Contains("Female"))
                row.DefaultCellStyle.BackColor = Color.Pink;                                
        }

Output : enter image description here

but on the other form the code is,

 foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Cells[5].Value.ToString().Contains("Female"))
                row.DefaultCellStyle.BackColor = Color.Pink;
            
        }

(that table has extra column so Gender goes to the sixth one)

this gives me an error like this.

System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Windows.Forms.DataGridViewCell.Value.get returned null.

I know that the second table has data and not null. Please can you tell me why the same code does not run on another form?

Update

I checked the data coming from the table by commenting out the error code and adding the line below,

MessageBox.Show(dataGridView1.Rows[0].Cells[5].Value.ToString());

it shows the messagebox with values I expected.

output: enter image description here

1

There are 1 best solutions below

3
On

As jmcilhinney said, null here is not database null.

You just need to turn off the allow editing of the table and it will work normally.

dataGridView1.AllowUserToAddRows = false;