Imports System.Collections.Generic
Public Class PrintDGV
Private Shared StrFormat As StringFormat ' Holds content of a TextBox Cell to write by DrawString
Private Shared StrFormatComboBox As StringFormat ' Holds content of a Boolean Cell to write by DrawImage
Private Shared CellButton As Button ' Holds the Contents of Button Cell
Private Shared CellCheckBox As CheckBox ' Holds the Contents of CheckBox Cell
Private Shared CellComboBox As ComboBox ' Holds the Contents of ComboBox Cell
Private Shared TotalWidth As Int16 ' Summation of Columns widths
Private Shared RowPos As Int16 ' Position of currently printing row
Private Shared NewPage As Boolean ' Indicates if a new page reached
Private Shared PageNo As Int16 ' Number of pages to print
Private Shared ColumnLefts As New ArrayList ' Left Coordinate of Columns
Private Shared ColumnWidths As New ArrayList ' Width of Columns
Private Shared ColumnTypes As New ArrayList ' DataType of Columns
Private Shared CellHeight As Int16 ' Height of DataGrid Cell
Private Shared RowsPerPage As Int16 ' Number of Rows per Page
Private Shared WithEvents PrintDoc As New System.Drawing.Printing.PrintDocument ' PrintDocumnet Object used for printing
Private Shared PrintTitle As String = "" ' Header of pages
Private Shared dgv As DataGridView ' Holds DataGrid Object to print its contents
Private Shared SelectedColumns As New List(Of String) ' The Columns Selected by user to print.
Private Shared AvailableColumns As New List(Of String) ' All Columns avaiable in DataGrid
Private Shared PrintAllRows As Boolean = True ' True = print all rows, False = print selected rows
Private Shared FitToPageWidth As Boolean = True ' True = Fits selected columns to page width , False = Print columns as showed
Private Shared HeaderHeight As Int16 = 0
Public Shared Sub Print_DataGridView(ByVal dgv1 As DataGridView)
Dim ppvw As PrintPreviewDialog
Try
' Getting DataGridView object to print
dgv = dgv1
' Getting all Coulmns Names in the DataGridView
AvailableColumns.Clear()
For Each c As DataGridViewColumn In dgv.Columns
If Not c.Visible Then Continue For
AvailableColumns.Add(c.HeaderText)
Next
' Showing the PrintOption Form
Dim dlg As New PrintOptions(AvailableColumns)
If dlg.ShowDialog() <> DialogResult.OK Then Exit Sub
' Saving some printing attributes
PrintTitle = dlg.PrintTitle
PrintAllRows = dlg.PrintAllRows
FitToPageWidth = dlg.FitToPageWidth
SelectedColumns = dlg.GetSelectedColumns
RowsPerPage = 0
ppvw = New PrintPreviewDialog
ppvw.Document = PrintDoc
ppvw.Document.PrinterSettings.DefaultPageSettings.Landscape = True
' Showing the Print Preview Page
If ppvw.ShowDialog() <> DialogResult.OK Then Exit Sub
' Printing the Documnet
PrintDoc.Print()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
End Try
End Sub