PrintPreviewDialog In Windows Forms DataGridView C# VB.NET

1:54:00 am 1 Comments

PrintPreviewDialog Control With DataGridView In Winforms Or Windows Forms Application Using C# And Vb.net

Printpreviewdialog in winforms windows forms datagridview C# vb.Net


In this post i'm explaining how to use printpreviewdialog with C# and vb.net to preview before printing datagridview in windows forms application.

Drag and place one printPreviewDialog control on the page, open it's property window and assign document to be previewed (printdocument1) to it's document property or assign it in code behind.

you can go to link mentioned above to know how to create printdocument.


C# CODE
01private void btnPrint_Click(object sender, EventArgs e)
02        {
03            //Assign printPreviewDialog properties
04            pvDialog.Document = printDocument1;
05            pvDialog.PrintPreviewControl.Zoom = 1;
06            pvDialog.ShowDialog();
07        }
08 
09        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
10        {
11            Bitmap dataGridViewImage = new Bitmap(this.dataGridView1.Width, this.dataGridView1.Height);
12            dataGridView1.DrawToBitmap(dataGridViewImage, new Rectangle(0, 0, this.dataGridView1.Width, this.dataGridView1.Height));
13            e.Graphics.DrawImage(dataGridViewImage, 0, 0);
14        }

VB.NET CODE
01Private Sub btnPrint_Click(sender As Object, e As EventArgs)
02 pvDialog.Document = printDocument1
03 pvDialog.PrintPreviewControl.Zoom = 1
04 pvDialog.ShowDialog()
05End Sub
06 
07Private Sub printDocument1_PrintPage(sender As Object, e As System.Drawing.Printing.PrintPageEventArgs)
08 Dim dataGridViewImage As New Bitmap(Me.dataGridView1.Width, Me.dataGridView1.Height)
09 dataGridView1.DrawToBitmap(dataGridViewImage, New Rectangle(0, 0, Me.dataGridView1.Width, Me.dataGridView1.Height))
10 e.Graphics.DrawImage(dataGridViewImage, 0, 0)
11End Sub

Build and run the code

Download Sample Code

1 comment: