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

时间:2012-08-30 17:56:16

标签: 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的效果不是我预期/希望的:字体颜色仍然是黑色,而不是黄色。

如何将字体颜色设为黄色?

2 个答案:

答案 0 :(得分:18)

你可以这样做:

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 :(得分:3)

  1. 要避免性能问题(与DataGridView中的数据量相关),请使用DataGridViewDefaultCellStyleDataGridViewCellInheritedStyle。参考:http://msdn.microsoft.com/en-us/library/ha5xt0d9.aspx

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

  3. 在这种情况下,您需要覆盖DataGridViewDefaultCellStyle,也许。

  4. <强> //修改
    在回复你对@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;
    
相关问题