温馨提示×

datagridview行颜色自定义如何做

小樊
82
2024-06-27 13:08:22
栏目: 编程语言

要自定义DataGridView的行颜色,可以使用DataGridView的RowsDefaultCellStyle属性来设置默认行样式,也可以在DataGridView的RowPrePaint事件中自定义每一行的颜色。

以下是两种方法的示例代码:

  1. 使用RowsDefaultCellStyle属性设置默认行样式:
dataGridView1.RowsDefaultCellStyle.BackColor = Color.LightGray;
dataGridView1.RowsDefaultCellStyle.ForeColor = Color.Black;
  1. 在RowPrePaint事件中自定义每一行的颜色:
private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
    if (e.RowIndex % 2 == 0)
    {
        dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightGray;
    }
    else
    {
        dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
    }
}

以上代码中,当行号为偶数时,设置行的背景颜色为浅灰色;当行号为奇数时,设置行的背景颜色为白色。您可以根据需求自定义每一行的颜色。

0