Click here to Skip to main content
Click here to Skip to main content

Another DataGridView Printer

By , 24 Dec 2012
 

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
  • Version 4.0 - Fixes and lots of new functionality!
    1. Bug Fixes
      1. Font resizing problem found by Member 8539779
      2. Rows that spanned multiple pages did not properly respect Right-to-Left Language setting
    2. New Features - Many thanks to everyone who suggested a new function or feature!!
      1. Set background colors/shading for Title, Subtitle and Footer
      2. Set border style and colors for Title, Subtitle and Footer
      3. Hide Columns - Specify a list of columns that will not be printed
      4. Fixed Columns - Specify a list of columns that will be printed on every page (good for rows spanning multiple pages). Respects Right-to-Left language setting
      5. Break on Value Change - Specify a column to monitor. When the value in a cell of this columns changes, a page break is inserted.
      6. Checkbox column now prints as an actual graphic checkbox.
  • Version 4.1 
    1. Greatly expanded Embedded Print process, now supports multiple pages and exposes the BeginPrint and PrintPage events.
    2. Added log/tracing facility
    3. Bug Fix - thanks and kudos to B. Marik for patience and help while I tracked this one down. 
  • Version 4.2
    1. Bug Fix - Print no longer throws at error. Thanks to Member 8757586 for finding it for me!
  • Version 4.3
    1. Bug Fix - Improved handling of checkboxes, added support for tristate checkbox.
    2. Bug Fix - Column headers would not print if the first column was hidden

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
No Biography provided

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

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
AnswerRe: Use with C++/climembernz5563 Oct '12 - 17:27 
GeneralRe: Use with C++/climemberaureolin4 Oct '12 - 12:09 
AnswerRe: Use with C++/climembernz5564 Oct '12 - 12:27 
GeneralRe: Use with C++/climemberaureolin4 Oct '12 - 13:57 
GeneralMy vote of 5memberMember 22628814 Sep '12 - 12:34 
GeneralAnother DataGridView Printer (View)memberEngone25 Aug '12 - 2:33 
GeneralRe: Another DataGridView Printer (View)memberaureolin25 Aug '12 - 7:53 
General[FIXED] Bug - cannot print DGV within new thread [modified]memberIvan Kalafatić29 Jul '12 - 10:01 
GeneralRe: [FIXED] Bug - cannot print DGV within new threadmemberaureolin31 Jul '12 - 17:03 
QuestionPrint other information with Data Grid ViewmemberSteve407727 Jul '12 - 8:13 
AnswerRe: Print other information with Data Grid Viewmemberaureolin31 Jul '12 - 17:08 
GeneralRe: Print other information with Data Grid ViewmemberSteve40771 Aug '12 - 3:13 
GeneralMy vote of 5memberrakh_vaf20 Jul '12 - 23:38 
Greate Job!
BugHideColumns is missing its setter.memberAhsanS17 Jul '12 - 20:19 
GeneralRe: HideColumns is missing its setter.memberaureolin21 Jul '12 - 13:44 
GeneralRe: HideColumns is missing its setter.memberAhsanS22 Jul '12 - 18:28 
GeneralMy vote of 5memberAhsanS16 Jul '12 - 1:25 
BugA bug in method RecalcRowHeightsmemberAhsanS16 Jul '12 - 1:09 
GeneralRe: A bug in method RecalcRowHeightsmemberaureolin21 Jul '12 - 13:40 
GeneralRe: A bug in method RecalcRowHeightsmemberAhsanS22 Jul '12 - 18:37 
QuestionHow to Wrap the column textmemberAhsanS15 Jul '12 - 22:01 
AnswerRe: How to Wrap the column textmemberaureolin21 Jul '12 - 13:48 
QuestionColumnHeaderCellHeight to override Column headers heightmemberMcPolu11 Jul '12 - 7:08 
GeneralMy vote of 5memberDaniele Di Sarli11 Jul '12 - 5:51 
Questionhandling empty cellsmemberMcPolu11 Jul '12 - 4:00 
AnswerRe: handling empty cellsmemberaureolin11 Jul '12 - 6:49 
GeneralRe: handling empty cellsmemberMcPolu11 Jul '12 - 6:50 
GeneralRe: handling empty cellsmemberaureolin11 Jul '12 - 8:21 
QuestionDynamic changing of EmbeddedPrintMultipageSetup rectangle?memberJWhattam18 Jun '12 - 18:51 
AnswerRe: Dynamic changing of EmbeddedPrintMultipageSetup rectangle?memberaureolin18 Jun '12 - 19:07 
QuestionHave to click twicememberdalebd6 Jun '12 - 15:54 
Questionprinting footermemberMarpri20 Apr '12 - 8:59 
AnswerRe: printing footermemberaureolin20 Apr '12 - 17:51 
QuestionPrint from a network connected printermemberMember 883039016 Apr '12 - 3:54 
AnswerRe: Print from a network connected printermemberaureolin16 Apr '12 - 6:36 
GeneralMy vote of 5memberDavid Ballantyne2 Apr '12 - 6:17 
QuestionRender without PrintingmemberDavid Ballantyne2 Apr '12 - 6:17 
SuggestionRe: Render without PrintingmemberAHSTech2 Jul '12 - 23:21 
GeneralRe: Render without Printingmemberaureolin6 Jul '12 - 5:39 
GeneralRe: Render without PrintingmemberAHSTech6 Jul '12 - 5:53 
QuestionHow do I print the color for each cell out with DataGridView Printer. VB code pleasememberblaze40129 Mar '12 - 9:34 
AnswerRe: How do I print the color for each cell out with DataGridView Printer. VB code pleasememberaureolin29 Mar '12 - 10:41 
QuestionVersion 4.2memberaureolin26 Mar '12 - 12:08 
AnswerRe: Version 4.2 [modified]memberDom201227 Mar '12 - 2:28 
AnswerRe: Version 4.2memberDaniele Di Sarli11 Jul '12 - 6:30 
BugGreat Work, but there´s an ExceptionmemberMember 875758624 Mar '12 - 12:28 
GeneralRe: Great Work, but there´s an Exceptionmemberaureolin24 Mar '12 - 16:51 
GeneralRe: Great Work, but there´s an Exceptionmemberaureolin26 Mar '12 - 12:07 
QuestionVersion 4.1memberaureolin23 Mar '12 - 11:55 
AnswerRe: Version 4.1memberJukka Blomqvist24 Mar '12 - 4:27 

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 24 Dec 2012
Article Copyright 2007 by aureolin
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid