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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Subhendu DePosted Dec 14, 2010, 3:59 AM
{
// 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;
}
}
Anthony ClarkePosted Dec 14, 2010, 5:04 AM
thanks Subhendu
CrishPosted Dec 14, 2010, 4:28 AM
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