Click here to Skip to main content
Licence CPOL
First Posted 16 Mar 2007
Views 439,060
Downloads 10,991
Bookmarked 318 times

Another DataGridView Printer

By aureolin | 25 Apr 2011
DataGridView printing encapsulated in a stand-alone object. Very easy to use! Updated to allow printing columns wider than one page.
1 vote, 0.9%
1
1 vote, 0.9%
2
1 vote, 0.9%
3
12 votes, 10.8%
4
96 votes, 86.5%
5
4.86/5 - 115 votes
3 removed
μ 4.80, σa 1.02 [?]

Introduction

I went looking for a class to do printing from a DataGridView, and none of them did all that I was looking for. I needed to print all pages, some pages, or the current selection; and I needed to not have objects, controls, or code from the printer object sprinkled through the rest of my code - i.e., it needed to be completely self-contained. Nothing I found met all those requirements, so I ended up writing my own.

Using the Code

To use the DGVPrinter class, you have two options. First, you can simply add the DGVPrinter.cs source file to your project, or second you can place the DLL in your "Bin" directory and add a reference to the DGVPrinter.dll to your project's references. In either case, to use the DGVPrinter, you will only need to add a "using DGVPrinter" to your code file, and create an instance of the object.

//
// The using block statement
//
using DGVPrinterHelper;
//
// The using block statement
//
imports DGVPrinterHelper;

For example, if you wanted to print a DataGridView when your user clicks a Print button on the toolbar, your code might look something like this:

//
// Printing the DataGridView Control
// in response to a toolbar button press
//
private void printToolStripButton_Click(object sender, EventArgs e)
{
    DGVPrinter printer = new DGVPrinter();
    printer.Title = "DataGridView Report";
    printer.SubTitle = "An Easy to Use DataGridView Printing Object";
    printer.SubTitleFormatFlags = StringFormatFlags.LineLimit | 
                                  StringFormatFlags.NoClip;
    printer.PageNumbers = true;
    printer.PageNumberInHeader = false;
    printer.PorportionalColumns = true;
    printer.HeaderCellAlignment = StringAlignment.Near;
    printer.Footer = "Your Company Name Here";
    printer.FooterSpacing = 15;

    printer.PrintDataGridView(datagridviewControl);
}
//
// Printing the DataGridView Control
// in response to a toolbar button press
//
Public Class Form1 
    Private Sub btnPrintGridview_Click(ByVal sender As System.Object, _
	ByVal e As System.EventArgs) Handles btnPrintGridView.Click
        Dim Printer = New DGVPrinter
        Printer.Title = "DataGridView Report"
        Printer.SubTitle = "An Easy to Use DataGridView Printing Object"
        Printer.SubTitleFormatFlags = StringFormatFlags.LineLimit Or _
					StringFormatFlags.NoClip
        Printer.PageNumbers = True
        Printer.PageNumberInHeader = False
        Printer.PorportionalColumns = True
        Printer.HeaderCellAlignment = StringAlignment.Near
        Printer.Footer = "Your Company Name Here"
        Printer.FooterSpacing = 15
        Printer.PrintDataGridView(Me.DataGridView1)
    End Sub

The basic interface used here provides a neat, one-stop-shop for printing a DataGridView. But, what if you want to have more control over the printing process? Say you'd like to save your users' print preferences or provide a default printer? To help you with this, DGVPrinter provides a more complex interface. Here's an example where the calling program provides overrides to the PrinterSettings and the DefaultPageSettings:

//
// Printing the DataGridView Control
// in response to a toolbar button press – 
// the myprintsettings and mypagesettings objects are objects used by the local
// program to save printer and page settings
//
private void printToolStripButton_Click(object sender, EventArgs e)
{
    DGVPrinter printer = new DGVPrinter();
    printer.Title = "DataGridView Report";
    printer.SubTitle = "An Easy to Use DataGridView Printing Object";
    printer.SubTitleFormatFlags = StringFormatFlags.LineLimit | 
        StringFormatFlags.NoClip;
    printer.PageNumbers = true;
    printer.PageNumberInHeader = false;
    printer.PorportionalColumns = true;
    printer.HeaderCellAlignment = StringAlignment.Near;
    printer.Footer = "Your Company Name Here";
    printer.FooterSpacing = 15;

    // use saved settings
    if (null != myprintsettings) 
        printer.PrintDocument.PrinterSettings = myprintsettings;
    if (null != mypagesettings)
        printer.PrintDocument.DefaultPageSettings = mypagesettings;

    if (DialogResult.OK == printer.DisplayPrintDialog())  // replace DisplayPrintDialog() 
						   // with your own print dialog
    {
        // save users' settings 
        myprintsettings = printer.PrinterSettings;
        mypagesettings = printer.PageSettings;

        // print without displaying the printdialog
        printer.PrintNoDisplay(datagridviewControl);
    }
}

DGVPrinter's various settings provide good control of all aspects of printing on the page. You can set the Title and Subtitles, add a footer, and control whether the page number prints in the header or footer. DGVPrinter supports Right-to-Left printing for non-Western languages and includes a drawing override for situations where a cell or column has onPaint overridden in the source DataGridView control. While the default styles for the printed DataGridView are taken from the source DataGridView control, DGVPrinter also provides many attributes that allow you to control the styling of almost every aspect of the printout.

History

  • Version 1.0 - Initial publication
  • Version 1.1 - Added footer handling, and allows the page number to print in the header or footer, and if it should print on the same line as the header or footer
  • Version 1.2 - Finally (I believe!), fixed the string/column alignment problems. Also prints cell background colors properly, respecting the alternating rows style
  • Version 1.3 - Added support for printing columns that contain images
  • Version 1.4 - Added support for printing directly to a provided Graphics object
  • Version 2.0 - Added support for printing images on the page
  • Version 3.0 - Breaking changes! Please read!
    1. Added support for cells/rows that span more than one page of depth. If a cell would run off the bottom of the page, the "KeepRowsTogether" property determines if a partial row is printed or a new page is started.
    2. Added support for Setting the styles for Row and Column Headers. The properties for setting Header cell styles changed names, and the return type of "PrintColumnHeaders" changed. This can cause your program to not compile/run!
    3. Added a default value so row headers will show up if they are supposed to be "visible"
    4. Added title and subtitle spacers. These will help give you control of the whitespace below the Title and Subtitle.
    5. Compiled version for VB and other language support
  • Version 3.1 - Fix cell background color printing
  • Version 3.2 - Fixes for Embedded Print function
  • Version 3.3 - Unlikely but possible breaking change
    1. Add Delegate to allow "Owner Drawing" of cells, including row and column headers
    2. Add better support for cell size, data size or proportional scaling of columns. The identifier 'StringHeight' has been changed to 'DataHeight' since the size of an image is now properly accounted for. This may break your code if you depend on this feature.
    3. Bug Fixes
  • Version 3.4 - Add support for Alternating Rows when ColumnStyles are overridden
  • Version 3.5 - More fixes for Alternating Rows ColumnStyles
  • Version 3.6 - Fix for Imbedded Image drawing; images now draw at original pixel sizes without scaling
  • Version 3.7 - Fix for large text wrapping

Gratitude, kudos and acknowledgements to everyone who suggested a feature or function or found a bug. DGV Printer just wouldn't be the same without everyone's ideas and input!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

aureolin



United States United States

Member


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Questionhow can the font size change in all of rows PinmemberMember 853977923:32 6 Feb '12  
AnswerRe: how can the font size change in all of rows Pinmemberaureolin8:08 7 Feb '12  
GeneralRe: how can the font size change in all of rows PinmemberMember 853977922:49 7 Feb '12  
Questionright to left Pinmembermahdishad1237:19 2 Feb '12  
QuestionThanks but how can i print particular column of datagrid view through this code? Pinmemberali nouman9:09 26 Jan '12  
QuestionUnable to pull datagridview data PinmemberBMarik13:13 20 Jan '12  
AnswerRe: Unable to pull datagridview data Pinmemberaureolin13:54 20 Jan '12  
GeneralRe: Unable to pull datagridview data PinmemberBMarik14:31 20 Jan '12  
QuestionRepeat frozen columns on each page Pinmemberijrr12:46 18 Jan '12  
AnswerRe: Repeat frozen columns on each page Pinmemberaureolin8:03 20 Jan '12  
GeneralMy vote of 5 Pinmembertolgasenol14:28 17 Jan '12  
GeneralMy vote of 5 Pingroup_Timbo_2:50 16 Jan '12  
Questionprint two datagridview in one page [modified] PinmemberMember 85397795:02 13 Jan '12  
AnswerRe: print two datagridview in one page Pinmemberaureolin15:56 13 Jan '12  
AnswerRe: print two datagridview in one page Pinmemberaureolin8:07 20 Jan '12  
GeneralRe: print two datagridview in one page PinmemberMember 85397798:59 20 Jan '12  
Questionvs2010 .NET 3,5 compile error Pinmembersusarac0:29 13 Jan '12  
AnswerRe: vs2010 .NET 3,5 compile error Pinmemberaureolin16:05 13 Jan '12  
QuestionMultiple datagridviews support PinmemberMember 27571920:20 12 Jan '12  
QuestionDraw CheckBox Column Pinmemberbaranils6:16 11 Jan '12  
Questionhow to change column header size?? Pinmemberkowal812:40 4 Jan '12  
AnswerRe: how to change column header size?? Pinmemberaureolin7:33 4 Jan '12  
GeneralMy vote of 4 Pinmemberjaj5:13 3 Dec '11  
QuestionHow can I increase the row height ? Pinmemberpositivesentient5:35 2 Dec '11  
AnswerRe: How can I increase the row height ? Pinmemberaureolin7:24 2 Dec '11  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120209.1 | Last Updated 25 Apr 2011
Article Copyright 2007 by aureolin
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid