[英]How can I make a DataGridView cell's font a particular color?
此代碼適用於使單元格的背景為藍色:
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;
}
}
要避免性能問題(與DataGridView
的數據量相關),請使用DataGridViewDefaultCellStyle
和DataGridViewCellInheritedStyle
。 參考: http : //msdn.microsoft.com/en-us/library/ha5xt0d9.aspx
您可以使用DataGridView.CellFormatting
根據以前的代碼限制繪制受影響的單元格。
在這種情況下,您可能需要覆蓋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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.