如何使 DataGridView 单元格的字体具有特定颜色? [英] How can I make a DataGridView cell's font a particular color?
本文介绍了如何使 DataGridView 单元格的字体具有特定颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这段代码可以很好地使单元格的背景变成蓝色:
This code works fine for making the cell's background Blue:
DataGridViewRow dgvr = dataGridViewLifeSchedule.Rows[rowToPopulate];
dgvr.Cells[colName].Style.BackColor = Color.Blue;
dgvr.Cells[colName].Style.ForeColor = Color.Yellow;
...但是 ForeColor 的效果不是我所期望/希望的:字体颜色仍然是黑色,而不是黄色.
...but the ForeColor's effects are not what I expected/hoped: the font color is still black, not yellow.
如何使字体颜色变黄?
推荐答案
您可以这样做:
dataGridView1.SelectedCells[0].Style
= new DataGridViewCellStyle { ForeColor = Color.Yellow};
您还可以在该单元格样式构造函数中设置任何样式设置(例如字体).
You can also set whatever style settings (font, for example) in that cell style constructor.
如果你想设置一个特定的列文本颜色,你可以这样做:
And if you want to set a particular column text color you could do:
dataGridView1.Columns[colName].DefaultCellStyle.ForeColor = Color.Yellow;
dataGridView1.Columns[0].DefaultCellStyle.BackColor = Color.Blue;
更新
因此,如果您想根据单元格中的值进行着色,则可以使用以下方法:
So if you want to color based on having a value in the cell, something like this will do the trick:
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;
}
}
这篇关于如何使 DataGridView 单元格的字体具有特定颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文