How to Print Windows Form in C#
By FoxLearn 8/25/2024 3:03:55 AM 10.59K
How to Print Windows Form in C#
Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "PrintWindowsForms" and then click OK
Drag and drop Label, Button, DataGridView, TextBox control from the Visual Studio toolbox onto your form designer, then you can layout your form as shown below.
We use the Northwind database to play demo. If you haven't got Northwind database, you can view How to download and restore Northwind database in SQL Server
Create an EF Model as shown below.
We will retrieve data from the Northwind database, then display data to DataGridView.
Open your form in the Designer view, then drag a PrintDocument
component from the Toolbox onto your form.
This will add a PrintDocument
component to your form’s components tray.
Drag a PrintPreviewDialog
and a PrintDialog
component from the Toolbox onto your form.
Double-click the buttons to generate Click
event handlers and write the code to manage the print preview and printing process.
Here is an example of how to implement these handlers:
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { //Draw form e.Graphics.DrawImage(bmp, 0, 0); } Bitmap bmp; private void btnPrint_Click(object sender, EventArgs e) { //Open print preview dialog Graphics g = this.CreateGraphics(); bmp = new Bitmap(this.Size.Width, this.Size.Height, g); Graphics mg = Graphics.FromImage(bmp); mg.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, this.Size); printPreviewDialog1.ShowDialog(); } private void Form1_Load(object sender, EventArgs e) { //Get product data using (NorthWindEntities db = new NorthWindEntities()) { productBindingSource.DataSource = db.Products.ToList(); } }
printDocument1_PrintPage is where you define what gets printed. In this example, the form itself is captured as an image and printed.
Run your application, click the "Print" button to start the actual printing process.
VIDEO TUTORIAL
- How to Encrypt and Decrypt a String in C#
- How to Live Currency Converter in C#
- How to Save TextBox, Label and CheckBox in User Settings in C#
- How to save files using SaveFileDialog in C#
- How to make an Alarm clock with sound in C#
- How to Display Images in DataGridView in C#
- How to Print DataGridView with Header & Footer with Landscape in C#
- How to Create a custom Progress Bar with Percentage in C#