c# - 如何使 DataGridView 单元格的字体具有特定颜色?

标签 c# winforms datagridview fonts datagridviewtextboxcell

此代码可以很好地使单元格的背景变为蓝色:

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/

相关文章:

c# - C# 中的 F# 扩展方法

c# - JSON.NET反序列化动态对象

c# - 将 using 语句与 WinForms 一起使用……好的做法?

.net - DataGridView 编辑模式

c# - 在 UserControl 中公开 DataGridView 的 Columns 属性并使其可通过 Designer 进行编辑

c# - 对 ListView 和 DataContext 的一些不满

c# - 为什么不允许使用没有 {} 的 try-catch 语句?

c# - NGen 和 Gacutil 最佳实践

C#:Cursor.Hide() 在 XP 上不起作用

visual-studio-2010 - 在 Visual Studio 中运行应用程序时,对 Access 数据库的更改不会持续存在