Hi,
Is there a way to change the colour of a datagridview cell based on a value?
Thanks for your time
Anthony
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Subhendu DeRank #1,108 · 1.7K reputationPosted Dec 13, 2010, 10:59 PM EST
{
// This is for mock datasource. You dont need it
ObjectSource[] _objectsource = new ObjectSource[]
{
new ObjectSource(1,"AAA"),
new ObjectSource(2,"BBB"),
new ObjectSource(3,"CCC"),
new ObjectSource(4,"DDD"),
new ObjectSource(5,"EEE")
};
dataGridView1.DataSource = _objectsource;
// This is what you want
// if the cell value > 3, then the background color of cell becomes Red
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (Convert.ToInt16(dataGridView1.Rows[i].Cells[0].Value) > 3)
{
dataGridView1.Rows[i].Cells[0].Style.BackColor = Color.Red;
}
}
}
}
// This is for mock datasource. You dont need it
public class ObjectSource
{
public int ID { get; set; }
public string Name { get; set; }
public ObjectSource(int id, string name)
{
ID = id;
Name = name;
}
}
CrishRank #1,486 · 1.1K reputationPosted Dec 13, 2010, 11:28 PM EST
You can refer this below code for datagridview cell color.
Example:
DataGridView1.Item(ColumnIndex, RowIndex).Style.BackColor = Color
DataGridView1.Item(ColumnIndex, RowIndex).Style.ForeColor = Color
or
DataGridView1.CurrentCell.Style.BackColor = Color
DataGridView1.CurrentCell.Style.ForeColor = Color
Anthony Clarke99 reputationPosted Dec 14, 2010, 12:04 AM EST
thanks Subhendu