假设您必须通过了解两件事来为某个单元格(不是该行的所有单元格)着色:
- 列的名称或索引。
- 将在单元格内部的值。
在这种情况下,您必须使用事件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;
}
}
}
结果你可以在这里看到
![在此处输入图像描述](https://i.stack.imgur.com/LvjM6.png)
因此,在这里您可以通过名称 row.Cells["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);
好吧...您需要例如为行中的某些单元格着色,例如 ##1 4 5 和 8 您必须使用单元格索引(它从 0 开始)。
代码看起来像
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;
}
}
}