How to DataGridView Printing

The DataGridView control offers an exceptional platform for presenting data in a customizable and visually appealing table format. It equips developers with an extensive range of properties, methods, and events that empower them to fine-tune every aspect of the control's appearance and behavior.

However, it is worth noting that the DataGridView control does not provide an inherent printing functionality, which could be seen as a limitation. Nevertheless, ingenious workarounds exist to overcome this limitation and achieve the desired printing capability.

One such approach involves incorporating a PrintDocument object into the project and utilizing the power of the PrintPage event. This event is triggered whenever a new page is ready to be printed, providing an opportune moment to execute the necessary printing operations.

datagridview-print

Within the PrintPage event handler, a Bitmap object is ingeniously created, serving as a canvas for rendering the DataGridView's contents. This Bitmap object acts as an intermediary, facilitating the transformation of the DataGridView into a printable format. By skillfully drawing the DataGridView onto this Bitmap object, the desired content is precisely captured and prepared for printing.

Full Source VB.NET
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM Authors" Dim connection As New SqlConnection(connectionString) Dim dataadapter As New SqlDataAdapter(sql, connection) Dim ds As New DataSet() connection.Open() dataadapter.Fill(ds, "Authors_table") connection.Close() DataGridView1.DataSource = ds DataGridView1.DataMember = "Authors_table" End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click PrintDocument1.Print() End Sub Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage Dim bm As New Bitmap(Me.DataGridView1.Width, Me.DataGridView1.Height) DataGridView1.DrawToBitmap(bm, New Rectangle(0, 0, Me.DataGridView1.Width, Me.DataGridView1.Height)) e.Graphics.DrawImage(bm, 0, 0) End Sub End Class

In order to run this vb.net project you have to drag two buttons ,one for load data and one for print command, and drag a PrintDocument control on your form . The following picture shows how to drag PrintDocument Object to your project.