如何将DataGridView单元格的字体设为特定颜色?

此代码适用于使单元格的背景为蓝色:

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; } } 
  1. 要避免性能问题(与DataGridView的数据量相关),请使用DataGridViewDefaultCellStyleDataGridViewCellInheritedStyle 。 参考: http : //msdn.microsoft.com/en-us/library/ha5xt0d9.aspx

  2. 您可以使用DataGridView.CellFormatting根据以前的代码限制绘制受影响的单元格。

  3. 在这种情况下,您可能需要覆盖DataGridViewDefaultCellStyle

//编辑
在回复你对@itsmatt的评论。 如果要将样式填充到所有行/单元格,则需要以下内容:

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