How to print datagrid in .NET? (VB.NET, C#, C++ for .NET Windows Forms)

The following article provides a programmatic approach to printing data within a .NET Windows Forms Datagrid.

Sometimes all you need to do is print a simple report you are already showing on a monitor screen. Learn how to do this using DataGridPrint class in the .NET Framework. You can do this easily in .NET without overheat of a third-party vendors reporting package.

The sample code for this article is available at http://www.skaterpro.net/DataGridColumnsTrial.zip
You will also need learn more about the DataGridColumns .NET assembly and download its trial version that is available for download from http://www.rustemsoft.com/DataGridColumns.htm

DataGrid Columns .NET assembly
More about DataGridColumns.dll
Download DataGridColumns.dll
Order DataGridColumns.dll



Basics

To print data within the Datagrid object that is settled down onto your .NET Windows Form, a custom code using the DataGridPrint class is used.

The service class is intended to help you to create a print output based on your datagrid content. The class has been included into DataGridColumns .NET assembly since it is built for .NET WinForms datagrid control and very helpful for your .NET datagrid design. It will help you to implement an application with a print preview and a print support.

Skater .NET Obfuscator
More about Skater .NET Obfuscator
Download Skater .NET Obfuscator
Order Skater .NET Obfuscator

The DataGridPrint class is used by the Print dialog and Print Preview dialog on your .NET form to draw the DataGrid object content that should be printed.


Syntax

DataGridPrint(PrintDocument1, DataGrid1, bBlackWhite)

PrintDocument1 - System.Drawing.Printing.PrintDocument reusable object that sends output to a printer
DataGrid1 - System.Windows.Forms.DataGrid object that content you are going to print
bBlackWhite - boolean parameter that defines if you like to use "Black and White" printing mode or you would like to send to printer the real coloring that your datagrid control has currently on your form.


How the .NET DataGrid Printing Works?

Printing datagrid content is provided directly by the application logic in the .NET Framework. You add a PrintDocument object to the project and handle the PrintPage event which is called every time a new page is to be printed. An object of the DataGridPrint class that renders the printed page using GDI+ graphics functions in the PrintPage event handler is used for a .NET PrintDocument object.
A print job is initiated by the PrintDocument's Print method. This starts the print job and raises one or more events. When the print job begins, a BeginPrint event occurs, followed by the PrintPage event for each page, followed by the EndPage event when the job is done. If the print job contains multiple pages, one PrintPage event will be raised for each page in the job making the PrintPage event to execute multiple times. The PrintPage event is the main event involved in printing documents. To send content to the printer you must handle this event and provide code to render the content in the PrintPage event handler.



In the above example when the Print button is clicked the custom frmPrint print dialog form will be open. The frmPrint form contains several dialog checkboxes and buttons. By using this custom Print setting form you can manage your datagrid printing output. You may define if the datagrids header title will be printed or not by assigning DataGridPrint class objects PrintTitle variable. Another Title property helps you to define the caption text on your datagrid print output. By using the Print setting form you can perform the following actions:
1. Call Print dialog and send datagrid print output directly to a printer device. The Print dialog box lets you select options for a particular print job. For example, you can specify the printer to use, the range of pages to print, and the number of copies.
2. Call Print Preview dialog. From this dialog, you can preview on the screen how each printed page of your .NET datagrid will appear, and select page layout, orientation, and the range of pages to print.
3. Call Page Setup dialog. The Page Setup dialog box lets you set the following attributes of the printed .NET datagrid page:
-The paper type (envelope, legal, letter, and so on)
-The paper source (manual feed, tractor feed, sheet feeder, and so on)
-The page orientation (portrait or landscape)
-The width of the page margins


Example

The following example creates a DataGridPrint object and prints the Datagrid.

VB .NET

Private PrintGrid As DataGridPrint
Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
Dim fpr As New frmPrint()
With fpr
.Title = DataGrid1.CaptionText
.ShowDialog()
If .Result > 0 Then
PrintGrid = New DataGridPrint(PrintDocument1, DataGrid1, .bBlackWhite)
PrintGrid.PrintTitle = .bTitle
PrintGrid.Title = .Title
Select Case .Result
Case 1 ' Print
' The Print method prints the datagrid without using a print dialog.
' Use a PrintDialog when you want to offer the user the ability to choose print settings.
If PrintDialog1.ShowDialog() = DialogResult.OK Then PrintDocument1.Print()
Case 2 ' Page Setup
PageSetupDialog1.ShowDialog()
Case 3 ' Preview
PrintPreviewDialog1.Icon = fpr.Icon
PrintPreviewDialog1.ShowDialog()
End Select
End If
End With
End Sub

' Specify the output to print by handling the PrintPage event
' and by using the Graphics included in the PrintPageEventArgs.
Private Sub printDocument1_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
' Print method of DataGridPrint class starts the custom datagrid's printing process.
e.HasMorePages = PrintGrid.Print(e.Graphics)
End Sub

C#

private DataGridPrint PrintGrid;
private void btnPrint_Click(object sender, System.EventArgs e)
{
frmPrint fpr = new frmPrint();
fpr.Title = DataGrid1.CaptionText;
fpr.ShowDialog();
if (fpr.Result > 0)
{
PrintGrid = new DataGridPrint(printDocument1, DataGrid1, fpr.bBlackWhite);
PrintGrid.PrintTitle = fpr.bTitle;
PrintGrid.Title = fpr.Title;
if (fpr.Result == 1) // Print
{
if (printDialog1.ShowDialog() == DialogResult.OK)
{
// The Print method prints the datagrid without using a print dialog.
// Use a PrintDialog when you want to offer the user the ability to choose print settings.
printDocument1.Print();
}
}
else if (fpr.Result == 2) // Page setup
{
pageSetupDialog1.ShowDialog();
}
else if (fpr.Result == 3) // Preview
{
printPreviewDialog1.Icon = fpr.Icon;
printPreviewDialog1.ShowDialog();
}
}
}

// Specify the output to print by handling the PrintPage event
// and by using the Graphics included in the PrintPageEventArgs.
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
// Print method of DataGridPrint class starts the custom datagrid's printing process.
e.HasMorePages = PrintGrid.Print(e.Graphics);
}


Summary

That is about it for this sample. We have added the .NET datagrid printing support to an application using DataGridPrint class, a process that involved vastly less effort than would have been required to code the printing mechanism by hand. If you would like to try out this sample application you will need the sample code for this article, the trial version of DataGridPrint and the DataGridColumns library. The download links for all of these are listed at the top of this article. The demo project contains a form with a DataGrid on it and prints or previews its columns. It uses the DataGridPrint class object in code that demonstrated above.
Further information about DataGridPrint and other controls by RustemSoft can be found at http://www.rustemsoft.com





Copyright © 2001-2018 Rustemsoft LLC











RustemSoft Software Products

We are glad to represent our software products designed for MS Windows. The trial versions are available for free, so you can fully evaluate it before spending your money. RustemSoft develops software of several categories:

XML Converter smart data transformation system Download Buy

Using XML Converter allows you to create XML document that will content the same data as your original MS Excel spreadsheet, MS Access database, Word document or csv/text file. XML Converter supports major databases such as ODBC, Oracle, MySQL and MS SQL Server. The resulting XML document will be built in strong compliance with XSL specifications. XML Converter allows you to create an XML database. This software gives you ability to generate an output as a set of XML tables. By using comprehensive interface you can adjust XML tags for final XML. Also this proved to be excellent because you can change the XSL style for XML output to what you wanted.

XML Converter two editions Download Buy

XML Converter is available in two editions: Standard Edition and Professional Edition. The Standard edition is an economical solution for users who need to view the Data Source and Target XML document in order to better understand how to built a best XML representation. With the Standard Edition, users can browse the Data Source and Target XML file to generate XML output easily using a graphical user interface, without adding costly instrumentation.
XML Converter Professional Edition is a complete solution for developers who want the browse facilities provided in the Standard Edition PLUS special modules, which provide command-line interface. Using the Professional Edition you will be able to call XML Converter strictly from your own application, with no user interface, allowing you to convert Data Source to XML in batch mode.
XML Converter includes XML View, XML Tree, XML Grid, and XML Script modes for final XML output editing. These editing features are presented in well-known XMLFox free XML Editor. All XML Converter Editions packages include that freeware convenient XML/XSD Editor. XMLFox Editor is our guarantee of fast, friendly XML editing and validation that meet your XML programming needs.

XMLFox Advance XML/XSD Editor Download Buy

Graphical XML editing and validation tool XMLFox Advance is XML/XSD editor for creating valid well-formed XML documents and/or XSD Schema. XMLFox Advance XML/XSD editor is the Windows based graphical tool for authoring, updating, exploring, well-formedness checking or validating XML documents. XMLFox Advance is an intuitive xml and xml schema(XSD) editor, allows the xml developer to create schemas and show a visual representation of what the xml document will look like for that schema.
XMLFox Advance Editor is a delimiter-aware XML data editor with markup-aware cut-and-paste operations, undo, rectangular selection, clear diagnostics and other innovative attractive tools to handle common XML/XSD editing tasks. Visual XML document editor, suited as a lightweight editor for document framework deployments. It features full XSD validation, but doesn't require a XSD (XML Schema Definition). XMLFox Advance includes XML View, XML Tree, XML Grid, and XML Script modes for editing.
XMLFox Advance is the tool for beginners to XSD schema (XML Schema Definition) as well as for professionals. It has visual Schema Tree representation that dynamically updates its XSD text. Those that need help in understanding schemas will find the Schema Tree inestimable, and developers maintaining other schemas will save hours of learning time with this XML editor. It is extremely configurable and fast enough. In XMLFox Advance you can output data to several other data format files. The Editor allows you export XML tables or whole XML to the following data files: TXT; convert into CSV (Comma Separated Value) file, convert into HTML page, create MS Access database, and create Excel file.

Skater .NET Obfuscator Download Buy

RustemSoft presents Skater .NET Obfuscator, an obfuscation tool for .NET code protection. It implements all known software protection techniques and obfuscation algorithms.
If you would like periodically obfuscate your .NET products the Skater .NET Obfuscator is for you. RustemSoft is using the Skater for internal needs securing all RustemSoft .NET executables and assemblies. Its command-line version running in batch mode is much useful for your scheduled products updates. You have to assign settings for an assembly in GUI version first. Then the batch obfuscate task will use the settings.
Main features of Skater .NET Obfuscator:
Prohibits reverse engineering
Obfuscated application usually is not recompilable
Processes any .NET application, executable or assembly
Encrypts string constants
Compatible with any .NET framework from 1.0 through 4.5
Control flow obfuscation stops decompilers and deobfuscators
Scrambles class names, method names, field names etc.

DataGridViewColumns .NET assembly for MS VS.NET Download Buy

We are presenting a software package for customizing your .NET (Visual Studio 2005 and later) Windows Forms DataGridView Columns. The DataGridViewColumns .NET assembly is DataGridView Columns software package specifically designed for .NET developers. The assembly allows you to use all strengths of the MS Windows .NET Forms DataGridView control without waiving the user interface elements your customers need. DataGridViewColumns dynamic link library contains the following DataGridView Columns: Combo (extended combobox), Memo column, DateTimePicker column. Also the assembly includes the formatting intelligent DateTimeColumn, NumericColumn, TextFractionsColumn, MaskedTextBox column controls that can mask the date, time, numbers as well as the text fractions. It gives you ability to manage the IP Address, SS#, Phone numbers, etc., and checks the validation, and automatically set the delimiter location. These Column classes are chock full of functionality that you wont find in the standard Microsoft .NET DataGridView Columns, that make it easy to build professional and forcing user interfaces.

DataGridColumns .NET assembly for MS VS.NET Download Buy

We are presenting a software package for customizing your .NET Windows Forms DataGrid Columns. The DataGridColumns .NET assembly is a DataGrid Columns Styles software package specifically designed for .NET developers. The assembly allows you to use all strengths of the MS Windows .NET Forms DataGrid control without waiving the user interface elements your customers need. DataGridColumns dynamic link library contains the following DataGrid Column Styles: combobox, XPButton column Style, Memo column Style, Button column Style, DateTimePicker column Style. Also the assembly includes the formatting intelligent DateTimeColumn, NumericColumn, TextFractionsColumn style controls that can mask the date, time, numbers as well as the text fractions. It gives you ability to manage the IP Address, SS#, Phone numbers, etc., and checks the validation, and automatically set the delimiter location.

ASP DataGridColumns assembly for MS VS.NET Download Buy

One of the most permanent challenges in designing user interfaces is figuring out how to display large amounts of data efficiently and intuitively without bewildering the user. The problem becomes particularly thorny when the interface must give the ability to easily update and store the data that the user needs to modify. We are presenting a software package for customizing your ASP .NET DataGrid server control's Columns. The ASP DataGridColumns .NET assembly from RustemSoft is a DataGrid Columns software package specifically designed for ASP .NET developers. The assembly allows you to use all strengths of the .NET DataGrid server control without waiving the user interface elements your customers need.

Sonswish - Oracle database browser Download Buy

Sonswish Oracle database browser is the Windows based graphical tool for database navigation, data updating, exploring, table relationships checking or validating Oracle database. Sonswish is an intuitive Oracle browser, allows the Oracle developer to create Oracle database objects (such as tables, views, procedures and so on) and show a visual representation of table relationships for that Oracle database.
Sonswish browser is a universal Oracle database browser with data updating operations, record filtering, printing, data format validation and other innovative attractive tools to handle common Oracle database browsing tasks. Sonswish allows to browse both structures and contents of databases managed by Oracle DBMS. Despite the fact that Sonswish cannot be positioned as a database's control application, our product has a number of most important features of database control application.
Sonswish allows to insert, delete, and update data records into database tables, remove whole tables. Furthermore, Sonswish provides interface to execute SQL statements of any complexity and for any purpose. Sonswish presents database as a hierarchical tree structure representation of all objects that belong to your Oracle database. A user can browse table structure, table indexes, primary keys, foreign keys, constraints and other table's objects. The software allows you export Oracle database tables/views to the following data files: txt, csv, html, mdb, Excel.

VB .NET and C# samples

Everyone was a beginner once. The faster we feed new people with good information, the faster they will become good members of the ".NET World". Here you can find some useful VB and C# examples. These sets of samples contain several high quality examples. These code samples show you how to work with comboboxes on Windows Forms and more