Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if datagridview cell is null or empty [duplicate]

I have to change the background color of the cells , when their value is string or empty, this is the code i have write similar to other codes here :

for (int rowIndex = 0; rowIndex < dataGridView1.RowCount; rowIndex++)
            {
             string conte = dataGridView1.Rows[rowIndex].Cells[7].Value.ToString()  ;
                if (string.IsNullOrEmpty(conte))
                {
                // dataGridView1.Rows[rowIndex].Cells[7].Style.BackColor = Color.Orange;
                }
                else
                 { dataGridView1.Rows[rowIndex].Cells[7].Style.BackColor = Color.Orange; }
        } 

the dataset is complete , show me the datagridview populated and the show me this error: enter image description here

How can i fix this?? Have another way to write the code?

like image 578
alejandro carnero Avatar asked Mar 31 '15 21:03

alejandro carnero


1 Answers

I would iterate through the cells using something like the following..

foreach (DataGridViewRow dgRow in dataGridView1.Rows)
{
    var cell = dgRow.Cells[7];
    if (cell.Value != null)   //Check for null reference
    {
        cell.Style.BackColor = string.IsNullOrEmpty(cell.Value.ToString()) ? 
            Color.LightCyan :   
            Color.Orange;       
    }
}
like image 187
Magic Mick Avatar answered Sep 16 '22 16:09

Magic Mick