Unable to change the background color of DataGridView cells

2.1k Views Asked by At

I'm attempting to loop through the rows within a datagridview and change the colour of a single cell depending on its stored value.

I have tried the two methods below but neither work and no exceptions are thrown.

1:

row.Cells[8].Style.BackColor = Color.Red;

2:

dgvProperties[row.Index, 8].Style.BackColor = Color.Red;

3 (another attempt since writing this question, also does not work):

dgvProperties.Rows[row.Index].Cells[8].Style.BackColor = Color.Red;

Any help appreciated.

3

There are 3 best solutions below

0
Mikev On BEST ANSWER

Try this, I guess this is what you are looking for..

for(int i = 0; i < dataGridView1.Rows.Count; i++)
        {
            int val = Int32.Parse(dataGridView1.Rows[i].Cells[2].Value.ToString());
            if (val < 5)
            {
               dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
            }

Credits: here

3
Be Ta On

try this:

row.Cells[i].Style["background-color"] = "red";

if does not work anyway you get the row in wrong way

0
HardCode On

Here is a VB.NET example of working code, however, it will be trivial to apply to your C# application:

Private Sub dgvResults_DataBindingComplete(
        ByVal sender As Object,
        ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs
        ) Handles dgvResults.DataBindingComplete

    Dim daysOpenThreshold As Integer = 10 'Some trivial value for this example.

    For Each r As DataGridViewRow In dgvResults.Rows

        If CInt(r.Cells(2).Value) >= daysOpenThreshold Then

            Dim style As New DataGridViewCellStyle
            style.BackColor = Color.Red
            style.ForeColor = Color.White

            r.DefaultCellStyle = style

        End If

    Next

End Sub