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

夙愿已清 提交于 2019-11-29 17:45:42

问题


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?


回答1:


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



回答2:


  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;


来源:https://stackoverflow.com/questions/12202751/how-can-i-make-a-datagridview-cells-font-a-particular-color

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