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

时光怂恿深爱的人放手 提交于 2019-11-30 11:47:45

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;
    }
}
  1. To avoid performance issues (related to the amount of data in the DataGridView), use DataGridViewDefaultCellStyle and DataGridViewCellInheritedStyle. Reference: http://msdn.microsoft.com/en-us/library/ha5xt0d9.aspx

  2. You could use DataGridView.CellFormatting to paint effected Cells on previous code limitations.

  3. 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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!