- Imports System.Drawing
- Imports System.Drawing.Printing
- Imports System.Data
- Imports System.Data.SqlClient
- Public Class Form1
- Dim EmpGrid As New DataGridView()
- Dim PrintDocument1 As New PrintDocument()
- Dim PrintPreviewDialog1 As New PrintPreviewDialog()
- Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
- Dim Provider As String = "Data Source=_DATA_SOURCE_HERE_;Initial Catalog=AdventureWorks;Integrated Security=True"
- Dim Connection As New SqlConnection(Provider)
- Try
- Connection.Open()
- Dim Command As New SqlCommand("SELECT TOP 20 FirstName, MiddleName, LastName, EmailAddress FROM Person.Contact", Connection)
- Dim Adapter As New SqlDataAdapter(Command)
- Dim EmpTable As New DataTable()
- Adapter.Fill(EmpTable)
- EmpGrid.DataSource = EmpTable
- PrintPreviewDialog1.PrintPreviewControl.Zoom = 1
- PrintPreviewDialog1.Document = PrintDocument1
- PrintPreviewDialog1.Show()
- AddHandler PrintDocument1.PrintPage, AddressOf PrintDocument1_PrintPage
- Catch Ex As Exception
- MessageBox.Show(Ex.Message)
- End Try
- EmpGrid.Dock = DockStyle.Fill
- Me.Controls.Add(EmpGrid)
- EmpGrid.AutoResizeColumns()
- End Sub
- Protected Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs)
- Dim ColumnCount As Integer = EmpGrid.ColumnCount
- Dim RowCount As Integer = EmpGrid.RowCount
- Dim CellTopPos As Integer = PrintDocument1.PrinterSettings.DefaultPageSettings.Margins.Top
- For Row = 0 To RowCount - 2
- Dim CellLeftPos As Integer = PrintDocument1.PrinterSettings.DefaultPageSettings.Margins.Left
- For Cell = 0 To ColumnCount - 1
- Dim CellValue As String = EmpGrid.Rows(Row).Cells(Cell).Value.ToString()
- Dim CellWidth = EmpGrid.Rows(Row).Cells(Cell).Size.Width + 10
- Dim CellHeight = EmpGrid.Rows(Row).Cells(Cell).Size.Height
- Dim Brush As New SolidBrush(Color.Black)
- e.Graphics.DrawString(CellValue, New Font("arial", 9), Brush, CellLeftPos, CellTopPos)
- e.Graphics.DrawRectangle(Pens.Black, CellLeftPos, CellTopPos, CellWidth, CellHeight)
- CellLeftPos += CellWidth
- Next
- CellTopPos += EmpGrid.Rows(Row).Cells(0).Size.Height
- Next
- End Sub
- End Class
VB.Net - Print Preview A DataGridView Control
The following code snippet demonstrates how to print preview a DataGridView control, using the PrintDocument and PrintPreviewDialog classes.
1 comment:
This is the only one post that worked in printing Datagridview directly without Report.
Post a Comment