This code is printing all the rows in a DataGridView, printing them on multiple pages if need be.
I made sure to use e.HasMorePages properly, and even stepped through the code, and it is properly exiting the PrintPage routine at the end of page 1, so that page 2 can be printed. But when it finishes, both pages are overlaid on top of each other instead of on their own pages.
Code:
' 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
Hasty edit: ColumnCount and RowCount are calculated when the the dataGridView is filled in the FormLoad sub