.net - 每 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
有什么帮助吗?
解决方案
您应该使用 DataGridView RowPrePaint或RowPostPaint事件来更改 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
推荐阅读
- python - 使用在所有单元测试模块之间共享的单个内存中 Sqlite 连接?
- kotlin - 重定向到 Ktor 中的绝对 URL
- android - 请修复 local.properties 文件中的“sdk.dir”属性。Studio 删除了路径中的斜杠。导入项目错误。怎么解决,调试?
- github - 在 github markdown 标头中使用较小的字体编写一个单词 ([link_name])
- gitlab - 是否可以更新 GitLab 路径?IE。https://change.this.path/username --> https://updated.new.path/username
- security - Symfony4。强制更改密码。重定向到更改密码站点
- vue.js - ESLint 期望代码中随机位置的表达式
- wavesplatform - 我如何从 RIDE 知道当前的区块链高度?
- java - 在 Java 中处理并行 API 调用的正确方法
- java - AWS 角色:权限如何从 EC2 实例转换到实例中运行的应用程序?