此代码可以很好地使单元格的背景变为蓝色:
DataGridViewRow dgvr = dataGridViewLifeSchedule.Rows[rowToPopulate];
dgvr.Cells[colName].Style.BackColor = Color.Blue;
dgvr.Cells[colName].Style.ForeColor = Color.Yellow;
...但是 ForeColor 的效果不是我所期望/希望的:字体颜色仍然是黑色,而不是黄色。
如何让字体颜色变成黄色?
最佳答案
你可以这样做:
dataGridView1.SelectedCells[0].Style
= new DataGridViewCellStyle { ForeColor = Color.Yellow};
您还可以在该单元格样式构造函数中设置任何样式设置(例如字体)。
如果您想设置特定列的文本颜色,您可以这样做:
dataGridView1.Columns[colName].DefaultCellStyle.ForeColor = Color.Yellow;
dataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Blue;
已更新
所以如果你想根据单元格中的值来着色,像这样的东西就可以了:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null && !string.IsNullOrWhiteSpace(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()))
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = new DataGridViewCellStyle { ForeColor = Color.Orange, BackColor = Color.Blue };
}
else
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = dataGridView1.DefaultCellStyle;
}
}
关于c# - 如何使 DataGridView 单元格的字体具有特定颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12202751/