-->

我怎样才能让一个DataGridView单元格的字体特定的颜色?(How can I make a

2019-06-27 14:55发布

此代码工作正常用于上述细胞的背景蓝色:

DataGridViewRow dgvr = dataGridViewLifeSchedule.Rows[rowToPopulate];
dgvr.Cells[colName].Style.BackColor = Color.Blue;
dgvr.Cells[colName].Style.ForeColor = Color.Yellow;

......但前景色的影响不出我所料/希望:字体颜色仍然是黑色的,不发黄。

我怎样才能让字体颜色发黄?

Answer 1:

你可以这样做:

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


Answer 2:

  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;


文章来源: How can I make a DataGridView cell's font a particular color?