Windows Forms: Print Windows Form in C#

How to print windows forms in c# using PrintDocument, PrintPreviewDialog

Step 1Click 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

c# print windows formsStep 2: Design your form as below

print windows forms in c#

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

Step 3: Create an EF Model as below

c# ef model

Step 4: Add code to handle your forms as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PrintWindowsForms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        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();
            }
        }
    }
}

VIDEO TUTORIALS