I've a simple form with a datagridview showing values from a ms sql table. I want that values over 400 in column of name "dc" become red (FONT IN RED). I've tried it over and over but I can´t get it done. Here's the code:
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
int cellval = Convert.ToInt32(row.Cells["dc"].Value);
if (cellval > 400)
{
row.DefaultCellStyle.BackCo开发者_如何学Pythonlor = Color.Red;
MessageBox.Show("O valor da célula é " + cellval, "WLic2010", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
Funiest, the thing of the MessageBox really proves that it understands my request as it only pops with the values over 400.
Help please!!
You are setting the style of a Row, not the cell (DataGridViewCell).
row.Cells["dc"].Style.BackColor = Color.Red;
Try this:
Use the "Style" property ->
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
Hope this answers your question.
Have you tried using the CellFormatting
event, there you can check the value of the current cell and then change the BackColor
To swap the font color, you need alter the ForeColor
property, try this way:
row.Cells["dc"].Style.ForeColor = Color.Red;
This should be solved if you use DataGridViewCell.Style.ForeColor, instead of DefaultCellStyle.BackColor.
精彩评论