假设您需要通过知道两件事情来给某个单元格(而不是整行的所有单元格)上色:
- 列的名称或索引。
- 将在单元格内的值。
在这种情况下,您需要使用事件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.Cells["Decade1Hours"].Style.BackColor = Color.LightSalmon;
}
}
}
您可以在此处查看结果。
![enter image description here](https://istack.dev59.com/LvjM6.webp)
因此,您可以通过其名称访问行中某个列的特定单元格
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;
}
}
}