Search code examples
mysqlvb.netprint-previewqprintpreviewdialog

Print data grid view skips the first row


I have created a print preview for the data grid view that I want to print. The code works fine but there is slight problem

Problem Screenshot:Print screenshot

In the data grid view row, the ID 1 is missing, it always starts from 2. How can I solve this problem? Please help.

My code:

 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
        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)
                If (newpage) Then
                    e.Graphics.DrawString(DataGridView1.Columns(cell.ColumnIndex).HeaderText, .Font, Brushes.Black, rc, fmt)
                Else
                    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

Solution

  • rows(0) is the first data row, not header row, while cell.RowIndex is 1, so change rows(cell.RowIndex) as rows(cell.RowIndex-1) :

    e.Graphics.DrawString(DataGridView1.Rows(cell.RowIndex - 1).Cells(cell.ColumnIndex).FormattedValue.ToString(), .Font, Brushes.Black, rc, fmt)