我有一个C#Winforms应用程序,我需要以编程方式设置单元格字体颜色。如果符合条件,字体应该是红色的。我已经确认条件检查是正确的,问题是在线如何在DataGridView中设置单元格的字体颜色?
dgv_Table.Rows[cell.RowIndex].Cells[cell.ColumnIndex].Style.ForeColor = Color.Blue;
其中“细胞”是我目前检查的细胞。这完全没有。即使我把它从循环中检查出来并且像这样检查:
dgv_Table.Rows[0].Cells[0].Style.ForeColor = Color.Blue;
它仍然没有任何作用。代码行位于Main()期间调用的辅助函数中。
如果我设置DefaultCellValue,那确实会改变视图,但不是我想要的。
private void Main_Load(object sender, EventArgs e)
{
dgv_Table.Rows[0].Cells[0].Style.ForeColor = Color.Blue;
dgv_Table.Rows[0].Cells[0].Style.BackColor = Color.Black;
foreach (DataGridViewRow row in dgv_Table.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
cell.Style.BackColor = Color.Black;
if (cell.OwningColumn.Name == "RiskName" && cell.Value.ToString() != "")
{
string wholeText = cell.Value.ToString();
int score = Convert.ToInt32(wholeText.Substring(wholeText.IndexOf("[") + 1, wholeText.IndexOf("–") - 1));
if (score > 300)
{
dgv_Table.Rows[cell.RowIndex].Cells[cell.ColumnIndex].Style.ForeColor = Color.Blue;
}
}
}
}
}
你是否尝试应用此更改?什么事件? –
当表单被加载时,它会通过并更改适当的单元格。 – Shay
你试过在DataGridView上调用'Invalidate()'吗? –