How can I make a DataGridView cell's font a particular color?

B. Clay Shannon picture B. Clay Shannon · Aug 30, 2012 · Viewed 70.6k times · Source

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;

...but the ForeColor's effects are not what I expected/hoped: the font color is still black, not yellow.

How can I make the font color yellow?

Answer

itsmatt picture itsmatt · Aug 30, 2012

You can do this:

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;

updated

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;
    }
}