比方說,你必須知道兩件事情上色某些細胞(行不是所有細胞):
- 列的名稱或索引。
- 將會在單元格內的值。
在你必須使用事件CellFormatting
在我來說,全髖關節置換情況下,我使用這樣
private void DgvTrucksMaster_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
foreach (DataGridViewRow row in dgvTrucksMaster.Rows)
{
if (Convert.ToInt32(row.Cells["Decade1Hours"].Value) > 0)
{
row.Cells["Decade1Hours"].Style.BackColor = Color.LightGreen;
}
else if (Convert.ToInt32(row.Cells["Decade1Hours"].Value) < 0)
{
// row.DefaultCellStyle.BackColor = Color.LightSalmon; // Use it in order to colorize all cells of the row
row.Cells["Decade1Hours"].Style.BackColor = Color.LightSalmon;
}
}
}
,並導致你可以在這裏看到
![enter image description here](https://i.stack.imgur.com/LvjM6.png)
所以在這裏您可以通過名稱訪問列中某一行的某個單元格行。細胞[「Decade1Hours」]
你怎麼知道這個名字? 那麼在我的情況下,我創建這樣的DataGridView的列。
var Decade1Hours = new DataGridViewTextBoxColumn()
{
Name = "Decade1Hours",
Width = 50,
DataPropertyName = "Decade1Hours",
ReadOnly = true,
DefaultCellStyle = new DataGridViewCellStyle()
{
Alignment = DataGridViewContentAlignment.MiddleCenter,
ForeColor = System.Drawing.Color.Black,
Font = new Font(font, FontStyle.Bold),
Format = "n2"
},
HeaderCell = new DataGridViewColumnHeaderCell()
{
Style = new DataGridViewCellStyle()
{
Alignment = DataGridViewContentAlignment.MiddleCenter,
BackColor = System.Drawing.Color.Blue
}
}
};
Decade1Hours.HeaderText = "Дек.1";
dgvTrucksMaster.Columns.Add(Decade1Hours);
嗯...你所需要例如着色部分細胞必須使用細胞指數(從0開始)像## 1 4 5和8排。
和代碼將樂像
private void DgvTrucksMaster_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
foreach (DataGridViewRow row in dgvTrucksMaster.Rows)
{
if (Convert.ToInt32(row.Cells[1].Value) > 0)
{
row.Cells[1].Style.BackColor = Color.LightGreen;
}
}
}
謝謝,對不起,這麼晚纔回復它的工作完美.. – preethi
那不是令人難以置信的效率低下?由於每次重繪所有記錄時,都會重繪任何單元格。 如果你正在採用這種方法,整個'foreach'子句不必在CellFormatting處理程序中,但它應該是'dataGridView1_DataBindingComplete'。 – 40Plot
或使用var Myrow = dataGridView1.Rows [e.RowIndex]而不是做循環 –