Академический Документы
Профессиональный Документы
Культура Документы
Rate this:
vote 1vote 2vote 3vote 4vote 5
This article will print all the records in a datagridview in tabular form
Download test application - 25.85 KB
Download pictures - 138.9 KB
Introduction
Few days ago, I had been working on an application, called Fee Management
System, which used to take the fee details from students and display the records
on the basis of certain search criteria in a grid. Then the fee collector could print
the entire details in the form of a report. Although, it was not a tedious task, the
integration of printing with the application took most of the time. So, I thought of
sharing my code with all the other developers who are working on the printing
of datagridview.
On the click of Get Customer Details button, we will load the Company Name,
Contact Name, Address, Postal Code and Phone from the Customers table on to
the grid and with the help of the Print button, we will print all the records in the
grid. The following code snippet will make a call to Customers table and load the
data on to the grid:
Hide Shrink
Copy Code
After executing the above code sample, we will have the grid with more than 90
records as shown in Figure 2:
Figure 2
And finally on click of Print button, we will print all the records in a tabular form as
shown in Figure 3:
The printdocument control plays a major role in this printing process. This control
has a PrintPage event that will have all the logic of printing. The spacing between
the cells, width of the cells, page margins are all handled in this event. Our print
click button event handler will invoke the PrintDialog control and there we can set
the printer, page and other settings. The following code sample will be used in the
Print button click event:
Hide Shrink
Copy Code
So, the print button click will show the Print Dialog as shown in Figure 4:
This is a standard print dialog and you can change the settings here. Now, on the
click of Print button in Print Dialog control, the PrintPage event
of printdocument gets invoked and prints all the records in the grid in tabular form
Copy Code
And finally, we will call the PrintPage event which plays the crucial role in this
printing process. The following code sample is used within the PrintPage event:
Hide Shrink
Copy Code
}
}
iRow++;
iTopMargin += iCellHeight;
}
//If more lines exist, print another page.
if (bMorePagesToPrint)
e.HasMorePages = true;
else
e.HasMorePages = false;
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
#endregion
----------------------------------------------------------------------//End Code Snippet
Here it is. You can see how easy the printing of datagridview records is. The
sample application is also attached for your reference. Let me know in case you
have any queries/issue