如何有条件地更改数据网格视图单元格的颜色
问题描述:
朋友们,
我有一个datagridview,我用sql server数据库中的表填充它。现在我想设置一个条件,如果例如datagridview的cell [2,3]的值为5,它的颜色必须是红色;
我该怎么做?
谢谢。
hi friends,
i have a datagridview that i fill it with a table in sql server database. now i want to set a condition that if for example cell[2,3] of datagridview has value of 5 it color must be red;
how can i do this?
thank you.
答
您可以在下面的CellFormatting事件中执行此操作。
You can do this on CellFormatting event like below.
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// give the column name which you want to check the value
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "ColumnName")
{
if (e.Value != null)
{
string stringValue = (string)e.Value;
if (stringValue == "5")
{
e.CellStyle.BackColor = Color.Red;
}
}
}
}
尝试 dataGridView1 .Rows [2] .Cells [3] .Style.BackColor = Color.Red