Thursday, March 28, 2013

This Example explains how to use PageSetupDialog In Windows Forms Winforms Application With C# And VB.NET to display page setup dialog and Print DataGridView.

PageSetupDialog In C# VB.NET Windows Forms Application

DataGridView is populated with Sql database.

To open PageSetupDialog In windows Forms and create bitmap image of data to print,Generate Click event of button by double clicking on it in design view and write following code.






C# CODE
01private void btnPrint_Click(object sender, EventArgs e)
02        {
03            PrintDocument printDocument1 = new PrintDocument();
04            printDocument1.PrintPage += new PrintPageEventHandler(this.printDocument1_PrintPage);
05            PageSetupDialog pageSetup = new PageSetupDialog();
06            pageSetup.Document = printDocument1;
07            pageSetup.PageSettings = printDocument1.DefaultPageSettings;
08 
09            if (pageSetup.ShowDialog() == DialogResult.OK)
10            {
11                printDocument1.DefaultPageSettings = pageSetup.PageSettings;
12                printDocument1.Print();
13            }
14         }
15 
16        private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
17        {
18            Bitmap dataGridViewImage = new Bitmap(this.dataGridView1.Width, this.dataGridView1.Height);
19            dataGridView1.DrawToBitmap(dataGridViewImage, new Rectangle(0, 0, this.dataGridView1.Width, this.dataGridView1.Height));
20            e.Graphics.DrawImage(dataGridViewImage, 0, 0);
21        }

VB.NET CODE
01Private Sub btnPrint_Click(sender As Object, e As EventArgs)
02 Dim printDocument1 As New PrintDocument()
03 printDocument1.PrintPage += New PrintPageEventHandler(AddressOf Me.printDocument1_PrintPage)
04 Dim pageSetup As New PageSetupDialog()
05 pageSetup.Document = printDocument1
06 pageSetup.PageSettings = printDocument1.DefaultPageSettings
07 
08 If pageSetup.ShowDialog() = DialogResult.OK Then
09  printDocument1.DefaultPageSettings = pageSetup.PageSettings
10  printDocument1.Print()
11 End If
12End Sub
13 
14Private Sub printDocument1_PrintPage(sender As Object, e As PrintPageEventArgs)
15 Dim dataGridViewImage As New Bitmap(Me.dataGridView1.Width, Me.dataGridView1.Height)
16 dataGridView1.DrawToBitmap(dataGridViewImage, New Rectangle(0, 0, Me.dataGridView1.Width, Me.dataGridView1.Height))
17 e.Graphics.DrawImage(dataGridViewImage, 0, 0)
18End Sub

0 comments:

Post a Comment