DataGridView打印预览丢失首行问题求助
DataGridView打印预览丢失首行(ID=1)的修复方案
问题说明
为DataGridView实现打印预览功能后,代码整体可运行,但打印内容始终丢失ID为1的行,从ID为2的行开始输出。
问题原因
原代码的newpage逻辑错误:首次进入循环时newpage=True,此时仅绘制了表头文本,未绘制第一行的单元格内容;循环结束后newpage设为False,mRow自增到1,导致后续直接从第二行开始绘制内容。
修复后的代码
Private Sub PrintDocument1_PrintPage(sender As System.Object, e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage Dim mRow As Integer = 0 Dim newpage As Boolean = True PrintDocument1.DefaultPageSettings.Landscape = True 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 ' 新页面顶部单独绘制表头 If newpage Then Dim xHeader As Single = e.MarginBounds.Left Dim hHeader As Single = 0 For Each col As DataGridViewColumn In .Columns Dim rcHeader As RectangleF = New RectangleF(xHeader, y, col.Width, .RowTemplate.Height) e.Graphics.DrawRectangle(Pens.Black, rcHeader.Left, rcHeader.Top, rcHeader.Width, rcHeader.Height) e.Graphics.DrawString(col.HeaderText, .Font, Brushes.Black, rcHeader, fmt) xHeader += rcHeader.Width hHeader = Math.Max(hHeader, rcHeader.Height) Next y += hHeader newpage = False End If ' 逐行绘制表格内容(包含首行) Do While mRow < .RowCount Dim row As DataGridViewRow = .Rows(mRow) Dim x As Single = e.MarginBounds.Left 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) e.Graphics.DrawString(row.Cells(cell.ColumnIndex).FormattedValue.ToString(), .Font, Brushes.Black, rc, fmt) x += rc.Width h = Math.Max(h, rc.Height) Next y += h mRow += 1 ' 判断是否需要分页 If y + .RowTemplate.Height > e.MarginBounds.Bottom Then e.HasMorePages = True newpage = True Exit Sub End If Loop e.HasMorePages = False End With End Sub
修复要点
- 表头绘制逻辑独立:仅在新页面开始时绘制表头,绘制完成后直接下移坐标,不占用首行的绘制位置。
- 行内容无差别绘制:移除原代码中
newpage对行内容的判断,确保首行(ID=1)能正常输出。 - 优化分页判断:使用行模板高度预估下一行位置,避免计算误差导致的分页异常。
- 明确结束标记:循环结束后设置
e.HasMorePages = False,确保打印流程正常收尾。
内容的提问来源于stack exchange,提问作者Salwa Hamim
相关产品推荐
相关产品推荐

