vb.net - 在 DataGridView VB.Net 中以颜色打印交替行
问题描述
我用数据填充 DatagridView,然后我想以交替颜色打印这些数据,但是当我执行 PrintPreview 时,我只看到我的列显示交替颜色。
Private Sub PrintDocument1_PrintPage(sender As System.Object, e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
With DataGridView1
Dim fmt As StringFormat = New StringFormat(StringFormatFlags.LineLimit)
fmt.LineAlignment = StringAlignment.Center
fmt.Trimming = StringTrimming.EllipsisCharacter
Dim y As Single = e.MarginBounds.Top - 50
Dim myBrush As Brush
Dim myBrush1 As Brush
Dim rowID As Integer = 0
myBrush = New SolidBrush(Color.AliceBlue)
myBrush1 = New SolidBrush(Color.White)
Do While mRow < .RowCount
Dim row As DataGridViewRow = .Rows(mRow)
Dim x As Single = e.MarginBounds.Left - 65
Dim h As Single = 0
For Each cell As DataGridViewCell In row.Cells
Dim rc As RectangleF = New RectangleF(x, y, cell.Size.Width, cell.Size.Height)
e.Graphics.DrawRectangle(Pens.Black, rc.Left, rc.Top, rc.Width, rc.Height)
If (newpage) Then
'e.Graphics.FillRectangle(myBrush, rc)
e.Graphics.DrawString(DataGridView1.Columns(cell.ColumnIndex).HeaderText, .Font, Brushes.Black, rc, fmt)
Else
If rowID = 0 Then
e.Graphics.FillRectangle(myBrush, rc)
rowID = 1
ElseIf rowID = 1 Then
e.Graphics.FillRectangle(myBrush1, rc)
rowID = 0
End If
e.Graphics.DrawString(DataGridView1.Rows(cell.RowIndex).Cells(cell.ColumnIndex).FormattedValue.ToString(), .Font, Brushes.Black, rc, fmt)
End If
x += rc.Width
h = Math.Max(h, rc.Height)
Next
newpage = False
y += h
mRow += 1
If y + h > e.MarginBounds.Bottom Then
e.HasMorePages = True
mRow -= 1
newpage = True
Exit Sub
End If
Loop
mRow = 0
End With
End Sub
我试图将
If rowID = 0 Then
e.Graphics.FillRectangle(myBrush, rc)
rowID = 1
ElseIf rowID = 1 Then
e.Graphics.FillRectangle(myBrush1, rc)
rowID = 0
End If
在其他地方,但我得到相同的结果。这种使用在 ASP.Net 中很容易,但现在我在 VB.Net 中工作。有任何想法吗?
解决方案
问题是您的画笔选择位于For Each
单元格的循环内。如果您不想更改每个单元格上的画笔,请不要选择每个单元格上的画笔。将选择画笔的代码放在外循环内但内循环外。
你应该做这样的事情:
Dim useAlternateBrush = False
Using standardBrush As New SolidBrush(Color.AliceBlue),
alternateBrush As New SolidBrush(Color.White)
Do While mRow < .RowCount
'...
Dim brush = If(useAlternateBrush, alternateBrush, standardBrush)
useAlternateBrush = Not useAlternateBrush
'...
For Each cell As DataGridViewCell In row.Cells
'...
'Use brush here.
'...
Next
Loop
End Using
请注意,SolidBrush
对象是使用Using
语句创建的,因此它们被隐式地设置在End Using
语句中。如果可能,应始终处置一次性对象,这几乎总是如此,并且应使用块创建和处置短期的一次性对象Using
。
推荐阅读
- php - 如何将 $_SESSION['user_login'] 更改为 laravel?
- python - 在 DataFlow 上运行光束管道时文件在关闭后被覆盖
- json - SQLite 在包含 JSON 的列内搜索
- rust - 采用 &Box 的因式分解方法
和 &T 作为参数 - c# - 如何使持久性后台任务信号成为asp.net核心中的范围服务?
- sql - Mysqlite 字母排序错位字符串以 alpha/beta 开头
- javascript - 请求包含其他信息的 Facebook 个人资料图片
- ruby-on-rails - 如何将布尔值播种到 Rails 应用程序中
- ios - 有没有办法先免费试用,然后一次性购买
- c# - 两个线程同时访问的单例类(引用类型)上的方法是否线程安全?