我正在嘗試更改datagridview中特定單元格的前景色。我想給不同的顏色在同一行中的不同單元格。更改DataGridView中特定單元格的forecolor
grid.Rows[row].Cells[col].Style.ForeColor = Color.Red
使用上述將更改所有的行顏色,而不僅僅是我想要更改的單元格。
有沒有辦法改變特定單元格的顏色 - 不影響行中的其他單元格?
看來我需要改變一些我不熟悉的Row屬性。
我正在嘗試更改datagridview中特定單元格的前景色。我想給不同的顏色在同一行中的不同單元格。更改DataGridView中特定單元格的forecolor
grid.Rows[row].Cells[col].Style.ForeColor = Color.Red
使用上述將更改所有的行顏色,而不僅僅是我想要更改的單元格。
有沒有辦法改變特定單元格的顏色 - 不影響行中的其他單元格?
看來我需要改變一些我不熟悉的Row屬性。
可以使用
dgv.Rows[curRowIndex].DefaultCellStyle.SelectionBackColor = Color.Blue;
使用上述將改變所有行的顏色,而不是隻是我想換
不,這是不正確的單元格。它只會改變指定索引處單元格的文本顏色(Forecolor)。
你需要檢查你是不是在你的代碼的其他地方設置行的forecolor。
下面的代碼工作正常,改變背部和前景色
//this will change the color of the text that is written
dataGridView1.Rows[0].Cells[4].Style.ForeColor = Color.Red;
//this will change the background of entire cell
dataGridView1.Rows[0].Cells[4].Style.BackColor = Color.Yellow;
@downvoter我可以知道downvote的原因嗎?我發佈的代碼經過測試並運行得非常好。 – Ehsan
使用CellFormatting事件:
void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridViewCell cell = grid.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (cell.Value is double && 0 == (double)cell.Value) { e.CellStyle.ForeColor = Color.Red; }
}
中,如果你可以寫你的條件去找尋特定的細胞
。
或試試這個。
private void ColorRows()
{
foreach (DataGridViewRow row in dataGridViewTest.Rows)
{
int value = Convert.ToInt32(row.Cells[0].Value);
row.DefaultCellStyle.BackColor = GetColor(value);
}
}
private Color GetColor(int value)
{
Color c = new Color();
if (value == 0)
c = Color.Red;
return c;
}
private void dataGridViewTest_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
ColorRows();
}
可能來自[鏈接] http://www.codeproject.com/Questions/203791/Changing-fore-color-of-a-dataGridView-cell –
是的,但它也適用於我 – Archit
如果您加載默認數據(datagridview.Datasource =表), 後立即應用的樣式或設置Row.DefaultStyle也不會影響到你下一次加載網格。
(也就是說,如果你設定的負載event.It風格不會得到affected.But如果再次調用同一個函數如單擊按鈕或東西后,它會工作)
解決有關此:
在DatagridView_DataBindingComplete事件中設置樣式。它會正常工作,並改變顏色,你也可以
你的代碼爲我工作,改變單細胞前景。 –