How to Print Windows Form in C#
By FoxLearn 8/25/2024 3:03:55 AM 10.77K
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 update UI from another thread in C#
- How to get CheckedListBox selected values in C#
- How to use Advanced Filter DataGridView in C#
- How to create a Notification Popup in C#
- How to Use Form Load and Button click Event in C#
- How to Link Chart /Graph with Database in C#
- How to Check SQL Server Connection in C#
- How to Generate Serial Key in C#