How to Print Windows Form in C#
By FoxLearn 8/25/2024 3:03:55 AM 10.68K
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 Print Text in a Windows Form Application Using C#
- How to fill ComboBox and DataGridView automatically in C#
- How to Read text file and Sort list in C#
- How to pass ListView row data into another Form in C#
- How to read and write to text file in C#
- How to make a Countdown Timer in C#
- How to Display selected Row from DataGridView to TextBox in C#
- How to Get all Forms and Open Form with Form Name in C#