[英]Print alternating rows in color din 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
块进行处置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.