Click here to Skip to main content
15,898,222 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello
I has an application created With Visual Studio 2015 it's worked Fine but in need when i want to print the data from datgridview with date of print and header and footer
iam using This Code
VB
Private mRow As Integer = 0
    Private newpage As Boolean = True

'''''''
And In Printdocument event
Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage


        ' sets it to show '...' for long text
        Dim fmt As StringFormat = New StringFormat(StringFormatFlags.LineLimit)
        fmt.LineAlignment = StringAlignment.Center
        fmt.Trimming = StringTrimming.EllipsisCharacter
        Dim y As Int32 = e.MarginBounds.Top
        Dim rc As Rectangle
        Dim x As Int32
        Dim h As Int32 = 0
        Dim row As DataGridViewRow

        ' print the header text for a new page
        '   use a grey bg just like the control
        If newpage Then
            row = DataGridView1.Rows(mRow)
            x = e.MarginBounds.Left
            For Each cell As DataGridViewCell In row.Cells
                ' since we are printing the control's view,
                ' skip invidible columns
                If cell.Visible Then
                    rc = New Rectangle(x, y, cell.Size.Width, cell.Size.Height)

                    e.Graphics.FillRectangle(Brushes.LightGray, rc)
                    e.Graphics.DrawRectangle(Pens.Black, rc)

                    ' reused in the data pront - should be a function
                    Select Case DataGridView1.Columns(cell.ColumnIndex).DefaultCellStyle.Alignment
                        Case DataGridViewContentAlignment.BottomRight,
                         DataGridViewContentAlignment.MiddleRight
                            fmt.Alignment = StringAlignment.Far
                            rc.Offset(-1, 0)
                        Case DataGridViewContentAlignment.BottomCenter,
                        DataGridViewContentAlignment.MiddleCenter
                            fmt.Alignment = StringAlignment.Center
                        Case Else
                            fmt.Alignment = StringAlignment.Near
                            rc.Offset(2, 0)
                    End Select

                    e.Graphics.DrawString(DataGridView1.Columns(cell.ColumnIndex).HeaderText,
                                            DataGridView1.Font, Brushes.Black, rc, fmt)
                    x += rc.Width
                    h = Math.Max(h, rc.Height)
                End If
            Next
            y += h

        End If
        newpage = False

        ' now print the data for each row
        Dim thisNDX As Int32
        For thisNDX = mRow To DataGridView1.RowCount - 1
            ' no need to try to print the new row
            If DataGridView1.Rows(thisNDX).IsNewRow Then Exit For

            row = DataGridView1.Rows(thisNDX)
            x = e.MarginBounds.Left
            h = 0

            ' reset X for data
            x = e.MarginBounds.Left

            ' print the data
            For Each cell As DataGridViewCell In row.Cells
                If cell.Visible Then
                    rc = New Rectangle(x, y, cell.Size.Width, cell.Size.Height)

                    ' SAMPLE CODE: How To 
                    ' up a RowPrePaint rule
                    'If Convert.ToDecimal(row.Cells(5).Value) < 9.99 Then
                    '    Using br As New SolidBrush(Color.MistyRose)
                    '        e.Graphics.FillRectangle(br, rc)
                    '    End Using
                    'End If

                    e.Graphics.DrawRectangle(Pens.Black, rc)

                    Select Case DataGridView1.Columns(cell.ColumnIndex).DefaultCellStyle.Alignment
                        Case DataGridViewContentAlignment.BottomRight,
                         DataGridViewContentAlignment.MiddleRight
                            fmt.Alignment = StringAlignment.Far
                            rc.Offset(-1, 0)
                        Case DataGridViewContentAlignment.BottomCenter,
                        DataGridViewContentAlignment.MiddleCenter
                            fmt.Alignment = StringAlignment.Center
                        Case Else
                            fmt.Alignment = StringAlignment.Near
                            rc.Offset(2, 0)
                    End Select

                    e.Graphics.DrawString(cell.FormattedValue.ToString(),
                                      DataGridView1.Font, Brushes.Black, rc, fmt)

                    x += rc.Width
                    h = Math.Max(h, rc.Height)
                End If

            Next
            y += h
            ' next row to print
            mRow = thisNDX + 1

            If y + h > e.MarginBounds.Bottom Then
                e.HasMorePages = True
                ' mRow -= 1   causes last row to rePrint on next page
                newpage = True
                Return
            End If
        Next

and event here
Private Sub PrintDocument1_BeginPrint(sender As Object, e As PrintEventArgs) Handles PrintDocument1.BeginPrint
       mRow = 0
       newpage = True
       PrintPreviewDialog1.PrintPreviewControl.StartPage = 0
       PrintPreviewDialog1.PrintPreviewControl.Zoom = 1.0
   End Sub

and button to print
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      PrintPreviewDialog1.Document = PrintDocument1
      PrintPreviewDialog1.ShowDialog()
  End Sub


What I have tried:

The Code Already Attached with the Example
Posted
Updated 6-Jun-18 23:25pm

1 solution

If you would like to add header and footer, you have to remember this:
1. calculate the distance that you need to reserve for the header and footer
2. print header
3. print data from datagridview (do not forget measuring text the space you need for footer)
4. print footer
5. go to next page if there's still something to print

VB
Dim linesPerPage As Single = 0
Dim line As String = Nothing
Dim count As Long = 0

' Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics)
linesPerPage -= 4 '1 for header and footer and 1 for space between text and header/footer

'print header
ev.Graphics.DrawString("Header's text goes here", printFont, Brushes.Black, leftMargin, yPos, New StringFormat())
ev.Graphics.DrawString("---", printFont, Brushes.Black, leftMargin, yPos, New StringFormat())

'print data
While count < linesPerPage
    'your logic to print datagridview data goes here
    line = DataGridView.Rows(count).Cell(0).Value 'gets first column data only
    ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, New StringFormat())
    count += 1
End While

'print footer
ev.Graphics.DrawString("---", printFont, Brushes.Black, leftMargin, yPos, New StringFormat())
ev.Graphics.DrawString("Footer's text goes here", printFont, Brushes.Black, leftMargin, yPos, New StringFormat())

' If more lines exist, print another page.
If (line IsNot Nothing) Then
    ev.HasMorePages = True
Else
    ev.HasMorePages = False
End If


For further details, please see: PrintDocument.PrintPage Event (System.Drawing.Printing)[^]
Printing of DataGridView[^]
 
Share this answer
 
Comments
Member 11691579 7-Jun-18 6:15am    
Thanks For Your Help But I have error With Your Code
ev and printFont and leftMargin and yPos Are Not declared
Maciej Los 7-Jun-18 6:18am    
Visit the first link, which provides to MSDN documentation.
Member 11691579 7-Jun-18 9:47am    
Okay I will thank You
simonlumga 27-Sep-19 8:26am    
can you provide full code
Maciej Los 30-Sep-19 5:56am    
There's almost full code. Please, refer articles under links

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900