myDataList.Add(new MyData { Name = "Charlie", Age = 35 });
// 绑定数据源
dataGridView1.DataSource = myDataList;
// 设置行样式
dataGridView1.RowsDefaultCellStyle.BackColor = Color.White;
dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
// 设置单元格样式
dataGridView1.CellFormatting += DataGridView1_CellFormatting;
}
private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
MyData data = dataGridView1.Rows[e.RowIndex].DataBoundItem as MyData;
if (data != null)
{
e.CellStyle.BackColor = data.RowColor;
}
}
}
```
在 CellFormatting 事件中,我们首先判断当前单元格是否为表头或行头,然后获取该行对应的 MyData 对象,并根据其 RowColor 属性来设置单元格的背景色。注意,由于 CellFormatting 事件会频繁触发,因此最好只在需要时才进行处理,以提高性能。