Search code examples
c#datagridviewcolorsdatagridviewcolumn

c# change color for a row if its not empty


I have a table an some values on it. If the Row Cell "Name" is not empty change color of background to violet.

Name    ID    Customers

Niky    1     yes       // here change background to violet
        2     no
Donna   3     yes       // here change background to violet
Baka    4     no        // here change background to violet
        5     yes
        6     no

I have tried this code but i doesnt work, dont know why:

 foreach (DataGridViewRow row1 in dataGridView1.Rows)
        {
            if (row1.Cells[0].Value != null)
            {
                row1.DefaultCellStyle.BackColor = Color.Violet;
            }
        }

Solution

  • The usual place to put this sort if code in within the DataBindingComplete event handler, either attach the event as below or using the designer:

    dataGridView1.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dataGridView1_DataBindingComplete);
    

    Then in the handler you have something like this:

    void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        foreach (DataGridViewRow row1 in dataGridView1.Rows)
        {
            if (row1.Cells.Cast<DataGridViewCell>().Any(c => c.Value == null || string.IsNullOrWhiteSpace(c.Value.ToString())))
            {
                row1.DefaultCellStyle.BackColor = Color.Violet;
            }
            else
            {
                row1.DefaultCellStyle.BackColor = Color.White;
            }
        }
    }
    

    In the code above I've changed your original code to now looks at all cells rather than just the first.


    You can also put the code in the CellFormatting event.