此代码打印DataGridView中的所有行,如果需要,可在多个页面上打印。
我确保正确使用e.HasMorePages,甚至逐步完成代码,并且在第1页末尾正确退出PrintPage例程,以便可以打印第2页。但是当它完成时,两个页面都叠加在彼此之上而不是在它们自己的页面上。
代码:
' These are all at the beginning of the class (form)
Private WithEvents printDocument1 As New Printing.PrintDocument
Private ColumnCount As Integer = 0
Private RowCount As Integer = 0
Private CurrRow As Integer = 0
Private CellTopPos As Integer = 0
Private CellLeftPos As Integer = 0
' this is the button on the form that runs the print routine
Private Sub btnPrint_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnPrint.Click
CurrRow = 0
PrintDocument1.Print()
End Sub
Private Sub printDocument1_PrintPage(ByVal sender As Object, _
ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles printDocument1.PrintPage
' start printing current row at top of page
With printDocument1
CellTopPos = .DefaultPageSettings.Margins.Top
While CellTopPos < .DefaultPageSettings.PaperSize.Width - _
.DefaultPageSettings.Margins.Bottom
' start printing current row at left of page
CellLeftPos = .DefaultPageSettings.Margins.Left
For Cell = 0 To ColumnCount - 1
Dim CellValue As String = _
grdSearch.Rows(CurrRow).Cells(Cell).Value.ToString()
Dim CellWidth = _
grdSearch.Rows(CurrRow).Cells(Cell).Size.Width + 50
Dim CellHeight = _
grdSearch.Rows(CurrRow).Cells(Cell).Size.Height
Dim Brush As New SolidBrush(Color.Black)
e.Graphics.DrawString(CellValue, _
New Font("Century Gothic", 10), Brush, CellLeftPos, CellTopPos)
e.Graphics.DrawRectangle(Pens.Black, CellLeftPos, _
CellTopPos, CellWidth, CellHeight)
CellLeftPos += CellWidth
Next
CellTopPos += grdSearch.Rows(CurrRow).Cells(0).Size.Height
CurrRow = CurrRow + 1
If CurrRow = RowCount Then Exit While
End While
End With
If CurrRow < RowCount Then
e.HasMorePages = True
Else
e.HasMorePages = False
End If
End Sub
仓促编辑:在FormLoad子文件中填充dataGridView时计算ColumnCount和RowCount
答案 0 :(得分:0)
好吧,我不能说我理解为什么,但是我明白了。就像我说的,我有另一个有效的例程,它在一个模块中,而这个当前的例程(不能正常工作),是在一个Form中。我将非工作表单打印例程移植到模块中,它突然开始正常工作。两者都是代码创建的,所以再次,不知道为什么差异,但嘿。有用。