How to Print DataGridView with Header and Footer in C#

By FoxLearn 7/26/2024 1:59:59 AM   7.81K
Printing a DataGridView with header and footer in C# involves several steps, including setting up the printing functionality, handling page breaks, and customizing headers and footers.

How to print DataGridView with Header and Footer in C#

Open your Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "PrintDataGridViewHeaderFooter" and then click OK

Drag and drop Button, DataGridView from the Visual toolbox on to your form designer, then design a simple form as shown below.

print datagridview 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

Add an EF model to your project as below

c# entity framework

Double-click on your form, then add a Form_Load event handler allows you to retrieve customer data from the Northwind database, then binding to your DataGridView.

private void Form1_Load(object sender, EventArgs e)
{
    using (NorthwindEntities db = new NorthwindEntities())
    {
        //Get data from northwind database
        customerBindingSource.DataSource = db.Customers.ToList();
    }
}

Add a click event handler to the Print button allows you to print data from DataGridView.

private void btnPrint_Click(object sender, EventArgs e)
{
    //Init print datagridview
    DGVPrinter printer = new DGVPrinter();
    printer.Title = "Customer Report";//Header
    printer.SubTitle = string.Format("Date: {0}", DateTime.Now.Date.ToString("MM/dd/yyyy"));
    printer.SubTitleFormatFlags = StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
    printer.PageNumbers = true;
    printer.PageNumberInHeader = false;
    printer.PorportionalColumns = true;
    printer.HeaderCellAlignment = StringAlignment.Near;
    printer.Footer = "FoxLearn";//Footer
    printer.FooterSpacing = 15;
    printer.PrintDataGridView(dataGridView);
}

To play demo you need to download DGVPrinter class, then copy to your project.

By following these steps, you should be able to print a DataGridView with headers and optionally footers in C#.

VIDEO TUTORIAL