首页 > 解决方案 > 每 2 行交替背景颜色

问题描述

我想每 2 行交替一次背景颜色。

例子:

在此处输入图像描述

我得到什么:

备用

我使用此代码,但它不能正常工作,如上图所示。

Dim contador As Integer
'Adding DataRow
For Each row As DataGridViewRow In dataCasados.Rows
    If contador Mod 2 = 0 Then
        pdfTable.DefaultCell.BackgroundColor = Color.RED
    Else
        pdfTable.DefaultCell.BackgroundColor = Color.BLUE
    End If

    For Each cell As DataGridViewCell In row.Cells
        pdfTable.AddCell(cell.Value.ToString())
    Next

    contador += 1

Next

有什么帮助吗?

标签: .netvb.net

解决方案


您应该使用 DataGridView RowPrePaintRowPostPaint事件来更改 Row 的背景颜色。使用该事件,您无需在Rows每次网格发生更改时循环整个集合:只影响需要重新绘制的行。

在这里,颜色被添加到rowColors数组中,但您可以在自定义属性中定义这些值。
步长/间隔也是如此,此处分配给该rowStep字段:

Private rowColors As Color() = {Color.Yellow, Color.LightGreen}
Private rowStep As Integer = 2 ' or 1 or 3 or...

Private Sub dataCasados_RowPostPaint(sender As Object, e As DataGridViewRowPostPaintEventArgs)
    Dim dgv = DirectCast(sender, DataGridView)
    Dim colorIndex As Integer = If((e.RowIndex / rowStep) Mod 2 = 0, 0, 1)
    dgv.Rows(e.RowIndex).DefaultCellStyle.BackColor = rowColors(colorIndex)
End Sub

作为一个外部循环,因为它显然是需要的:

Dim dgv = dataCasados
For Each row As DataGridViewRow In dgv.Rows
    Dim colorIndex As Integer = If((row.Index / rowStep) Mod 2 = 0, 0, 1)
    dgv.Rows(row.Index).DefaultCellStyle.BackColor = rowColors(colorIndex)
Next

推荐阅读