winform中dataGridView隔行显示不同的背景色,鼠标移动上显示不同颜色,离开后变回原色
先设置奇数行颜色,这个有个自带的属性AlternatingRowsDefaultCellStyle
dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue; //奇数行颜色
再在dataGridView上添加两个事件,分别是CellMouseLeave和CellMouseMove
代码如下:
private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{ if (e.RowIndex > -1)
{
if (e.RowIndex % 2 == 0)
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
else
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.AliceBlue; }
} private void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
{ if (e.RowIndex > -1)
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.PowderBlue;
}
}