private void Form1_Load(object sender, EventArgs e) { // 创建数据源 List<MyData> myDataList = new List<MyData>();

动态 未结 0 75
小小草
小小草 LV1 2023年9月23日 23:40 发表
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 事件会频繁触发,因此最好只在需要时才进行处理,以提高性能。
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复