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?
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;
}
}
To avoid performance issues (related to the amount of data in the
DataGridView
), useDataGridViewDefaultCellStyle
andDataGridViewCellInheritedStyle
. Reference: http://msdn.microsoft.com/en-us/library/ha5xt0d9.aspxYou could use
DataGridView.CellFormatting
to paint effected Cells on previous code limitations.In this case, you need to overwrite the
DataGridViewDefaultCellStyle
, maybe.
//edit
In Reply to your comment on @itsmatt. If you want to populate a style to all rows/cells, you need something like this:
// Set the selection background color for all the cells.
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.White;
dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Black;
// Set RowHeadersDefaultCellStyle.SelectionBackColor so that its default
// value won't override DataGridView.DefaultCellStyle.SelectionBackColor.
dataGridView1.RowHeadersDefaultCellStyle.SelectionBackColor = Color.Empty;
// Set the background color for all rows and for alternating rows.
// The value for alternating rows overrides the value for all rows.
dataGridView1.RowsDefaultCellStyle.BackColor = Color.LightGray;
dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.DarkGray;
来源:https://stackoverflow.com/questions/12202751/how-can-i-make-a-datagridview-cells-font-a-particular-color