1
votes

I have a datagridview that has two columns, what i want to do is iterate over the rows and colour only the second row based on a condition, so far i have this:

                foreach (DataGridViewRow row in dsgDataGrid.Rows)
                {
                    var stock = Convert.ToInt32(row.Cells[1].Value);

                    if (stock == 0)
                    {
                        row.DefaultCellStyle.BackColor = Color.Red;
                    }
                    if (stock >= 1 && stock <= 5)
                    {
                        row.DefaultCellStyle.BackColor = Color.LightSalmon;
                    }
                }

That gets the entire row red (where the value is 0) but can anyone advise on how to only affect the cell in the second column based on the condition?

Thanks.

2

2 Answers

3
votes

You can set the BackColor of a specific cell by using the Cells property of the DataGridViewRow with the desired index, for example:

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

You can also use the name of column:

row.Cells["ColumnName"].Style.BackColor = Color.Red;
0
votes

You'll be able to set the Color on a specific cell of a row with the following line of code:

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

Or you could also loop through columns instead and set the color on each cell depending on the value of the cell your looking up.