Click here to Skip to main content
13,150,622 members (47,137 online)
Click here to Skip to main content
Add your own
alternative version

Stats

310.9K views
37.5K downloads
95 bookmarked
Posted 22 Jul 2008

Printing of DataGridView

, 31 Jul 2008
Rate this:
Please Sign up or sign in to vote.
This article will print all the records in a datagridview in tabular form

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.

Using the Code

To simplify things, I made a sample application and used the Customers table of Northwind database. In this application, we will have a simple form that will have two button controls, one datagridview control and a print<code>document control. The form will look as under (Figure 1):

Figure 1

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:

>//Start Code Snippet
-----------------------------------------------------------------------
#region Get Customer Details Button Click Event
/// <span class="code-SummaryComment"><summary></span>
/// Handles the customer details button click
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name=""sender""></param></span>
/// <span class="code-SummaryComment"><param name=""e""></param></span>
private void btnCustomerDetails_Click(object sender, EventArgs e)
{
    Cursor.Current = Cursors.WaitCursor;
    SqlConnection sqlConnection = null;
    SqlCommand sqlCommand = null;
    SqlDataReader sqlReader = null;

    try
    {
        string strQuery = "SELECT CompanyName, ContactName, Address, PostalCode,
            Phone FROM Customers";
        sqlConnection = new SqlConnection(strConnectionString);
        sqlConnection.Open();
        sqlCommand = new SqlCommand(strQuery, sqlConnection);
        sqlReader = sqlCommand.ExecuteReader();
        while (sqlReader.Read())
        {
            object[] row = { sqlReader[0], sqlReader[1], sqlReader[2], sqlReader[3],
            sqlReader[4] };
            dataGridView1.Rows.Add(row);
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK,
            MessageBoxIcon.Error);
        return;
    }
    finally
    {
        Cursor.Current = Cursors.Default;
        sqlConnection.Close();
        if (sqlReader != null)
        {
            sqlReader.Dispose();
            sqlReader = null;
        }
        if (sqlCommand != null)
        {
            sqlCommand.Dispose();
            sqlCommand = null;
        }
    }
}
#endregion
-----------------------------------------------------------------------
//End Code Snippet

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:

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:

//Start Code Snippet
-----------------------------------------------------------------------
#region Print Button Click Event
/// <span class="code-SummaryComment"><summary></span>
/// Handles the print button click event
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name=""sender""></param></span>
/// <span class="code-SummaryComment"><param name=""e""></param></span>
private void btnPrint_Click(object sender, EventArgs e)
{           
    //Open the print dialog
    PrintDialog printDialog = new PrintDialog();            
    printDialog.Document = printDocument1;
    printDialog.UseEXDialog = true;    
    //Get the document
    if (DialogResult.OK == printDialog.ShowDialog())
    {
        printDocument1.DocumentName = "Test Page Print";                
        printDocument1.Print();
    }
    /*
    Note: In case you want to show the Print Preview Dialog instead of 
    Print Dialog then comment the above code and uncomment the following code
    */

    //Open the print preview dialog
    //PrintPreviewDialog objPPdialog = new PrintPreviewDialog();
    //objPPdialog.Document = printDocument1;
    //objPPdialog.ShowDialog();
}
#endregion
-----------------------------------------------------------------------
//End Code Snippet

So, the print button click will show the Print Dialog as shown in Figure 4:

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 as show in figure 4. The PrintDialog’s Document property is set to the printdocument control and to print the document, invoke the Print method of printDocument control. This will invoke the PrintPage event of printDocument. We have also handled the BeginPrint event of printDocument, where we formatted the string to be printed. The following code sample will be called from the BeginPrint event:

//Start Code Snippet
-----------------------------------------------------------------------
#region Begin Print Event Handler
/// <span class="code-SummaryComment"><summary></span>
/// Handles the begin print event of print document
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name=""sender""></param></span>
/// <span class="code-SummaryComment"><param name=""e""></param></span>
private void printDocument1_BeginPrint(object sender,
    System.Drawing.Printing.PrintEventArgs e)
{
    try
    {
        strFormat = new StringFormat();
        strFormat.Alignment = StringAlignment.Near;
        strFormat.LineAlignment = StringAlignment.Center;
        strFormat.Trimming = StringTrimming.EllipsisCharacter;

        arrColumnLefts.Clear();
        arrColumnWidths.Clear();
        iCellHeight = 0;
        iCount = 0;
        bFirstPage = true;
        bNewPage = true;

        // Calculating Total Widths
        iTotalWidth = 0;
        foreach (DataGridViewColumn dgvGridCol in dataGridView1.Columns)
        {
            iTotalWidth += dgvGridCol.Width;
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
#endregion
-----------------------------------------------------------------------
//End Code Snippet

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:

//Start Code Snippet
-----------------------------------------------------------------------
#region Print Page Event
/// <span class="code-SummaryComment"><summary></span>
/// Handles the print page event of print document
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name=""sender""></param></span>
/// <span class="code-SummaryComment"><param name=""e""></param></span>
private void printDocument1_PrintPage(object sender,
    System.Drawing.Printing.PrintPageEventArgs e)
{
    try
    {
        //Set the left margin
        int iLeftMargin = e.MarginBounds.Left;
        //Set the top margin
        int iTopMargin = e.MarginBounds.Top;
        //Whether more pages have to print or not
        bool bMorePagesToPrint = false;
        int iTmpWidth = 0;             

        //For the first page to print set the cell width and header height
        if (bFirstPage)
        {
            foreach (DataGridViewColumn GridCol in dataGridView1.Columns)
            {
                iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
                    (double)iTotalWidth * (double)iTotalWidth *
                    ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
                    GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;

                // Save width and height of headers
                arrColumnLefts.Add(iLeftMargin);
                arrColumnWidths.Add(iTmpWidth);
                iLeftMargin += iTmpWidth;
            }
        }
        //Loop till all the grid rows not get printed
        while (iRow <= dataGridView1.Rows.Count - 1)
        {
            DataGridViewRow GridRow = dataGridView1.Rows[iRow];
            //Set the cell height
            iCellHeight = GridRow.Height + 5;
            int iCount = 0;
            //Check whether the current page settings allows more rows to print
            if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
            {
                bNewPage = true;
                bFirstPage = false;
                bMorePagesToPrint = true;
                break;
            }
            else
            {
                if (bNewPage)
                {
                    //Draw Header
                    e.Graphics.DrawString("Customer Summary", 
                        new Font(dataGridView1.Font, FontStyle.Bold),
                        Brushes.Black, e.MarginBounds.Left, 
                        e.MarginBounds.Top - e.Graphics.MeasureString("Customer Summary",
                        new Font(dataGridView1.Font,FontStyle.Bold),
                        e.MarginBounds.Width).Height - 13);

                    String strDate = DateTime.Now.ToLongDateString() + " " +
                        DateTime.Now.ToShortTimeString();
                    //Draw Date
                    e.Graphics.DrawString(strDate, 
                        new Font(dataGridView1.Font, FontStyle.Bold), Brushes.Black,
                        e.MarginBounds.Left + 
                        (e.MarginBounds.Width - e.Graphics.MeasureString (strDate, 
                        new Font(dataGridView1.Font, FontStyle.Bold),
                        e.MarginBounds.Width).Width), 
                        e.MarginBounds.Top - e.Graphics.MeasureString("Customer Summary",
                        new Font(new Font(dataGridView1.Font, FontStyle.Bold), 
                        FontStyle.Bold), e.MarginBounds.Width).Height - 13);

                    //Draw Columns                 
                    iTopMargin = e.MarginBounds.Top;
                    foreach (DataGridViewColumn GridCol in dataGridView1.Columns)
                    {
                        e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),    
                            new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                            (int)arrColumnWidths[iCount], iHeaderHeight));

                        e.Graphics.DrawRectangle(Pens.Black,             
                            new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                            (int)arrColumnWidths[iCount], iHeaderHeight));

                        e.Graphics.DrawString(GridCol.HeaderText,
                            GridCol.InheritedStyle.Font,
                            new SolidBrush(GridCol.InheritedStyle.ForeColor),
                            new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                            (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                        iCount++;
                    }
                    bNewPage = false;
                    iTopMargin += iHeaderHeight;
                }
                iCount = 0;
                //Draw Columns Contents                
                foreach (DataGridViewCell Cel in GridRow.Cells)
                {
                    if (Cel.Value != null)
                    {
                        e.Graphics.DrawString(Cel.Value.ToString(),
                            Cel.InheritedStyle.Font,
                            new SolidBrush(Cel.InheritedStyle.ForeColor),
                            new RectangleF((int)arrColumnLefts[iCount],
                            (float)iTopMargin,
                            (int)arrColumnWidths[iCount], (float)iCellHeight),
                            strFormat);
                    }
                    //Drawing Cells Borders 
                    e.Graphics.DrawRectangle(Pens.Black, 
                        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                        (int)arrColumnWidths[iCount], iCellHeight)); 
                    iCount++;
                }
            }
            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/issues.

Happy programming!

License

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

Share

About the Author

Life with .NET
Software Developer (Senior)
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
Questioncode use Pin
Member 1197550123-Aug-17 15:28
memberMember 1197550123-Aug-17 15:28 
AnswerRe: code use Pin
Member 1113415213-Sep-17 21:57
memberMember 1113415213-Sep-17 21:57 
Questionobjects not declared Pin
Member 1261350722-Mar-17 17:54
memberMember 1261350722-Mar-17 17:54 
PraiseThis works like a charm. Thanks a million. Pin
Member 1140135122-Feb-17 14:11
memberMember 1140135122-Feb-17 14:11 
PraiseThanks Pin
morTezacs23-Dec-16 9:15
groupmorTezacs23-Dec-16 9:15 
QuestionWhat is arrColumnLefts Pin
Nganku Junior10-Nov-16 7:38
memberNganku Junior10-Nov-16 7:38 
QuestionCode download Links are not active Pin
Nganku Junior13-Oct-16 5:50
memberNganku Junior13-Oct-16 5:50 
QuestionPrinting of DataGridView Pin
Member 1104044614-Sep-16 11:56
memberMember 1104044614-Sep-16 11:56 
QuestionError: Pin
Member 1264827321-Jul-16 23:51
memberMember 1264827321-Jul-16 23:51 
QuestionMay I add this code set to a fee utility that prints CSV files? Pin
PhilMcGahan19-May-16 8:49
memberPhilMcGahan19-May-16 8:49 
QuestionPrint a dataGridView complete, even when not in the Windows. No bitmap Pin
Member 1245949614-Apr-16 9:57
memberMember 1245949614-Apr-16 9:57 
QuestionRe: Print a dataGridView complete, even when not in the Windows. No bitmap Pin
yaacoub Amna (‫فخاقازان‬‎)6-Oct-16 0:57
memberyaacoub Amna (‫فخاقازان‬‎)6-Oct-16 0:57 
Questionthank u .its working Pin
bala107278@gmail.com5-Apr-16 7:57
memberbala107278@gmail.com5-Apr-16 7:57 
Praisegood very use ful Pin
crazyradha26-Mar-16 15:10
membercrazyradha26-Mar-16 15:10 
Praisegood very use ful Pin
crazyradha26-Mar-16 15:10
membercrazyradha26-Mar-16 15:10 
PraiseExcellent Pin
LogicPlayer12-Mar-16 0:29
memberLogicPlayer12-Mar-16 0:29 
QuestionError:Index was out of Range Pin
Member 122689089-Mar-16 19:26
memberMember 122689089-Mar-16 19:26 
AnswerRe: Error:Index was out of Range Pin
LogicPlayer12-Mar-16 0:36
memberLogicPlayer12-Mar-16 0:36 
QuestionWhat the necessity of the formula in iTmpWidth? Pin
Member 123466602-Mar-16 8:42
memberMember 123466602-Mar-16 8:42 
QuestionAlternate Print Record Pin
Member 122686763-Feb-16 19:16
memberMember 122686763-Feb-16 19:16 
QuestionHi, Can I print some more info Pin
Tzvetin12-Jan-16 11:28
memberTzvetin12-Jan-16 11:28 
Questionreverses Columns ?? Pin
dido_e_6075-Dec-15 9:07
memberdido_e_6075-Dec-15 9:07 
GeneralThanks for your help ! Pin
Member 1201953629-Sep-15 23:07
memberMember 1201953629-Sep-15 23:07 
QuestionSir Pin
Member 1197735427-Sep-15 5:42
memberMember 1197735427-Sep-15 5:42 
Questionyou dont explain almost nothing Pin
Member 117167353-Sep-15 9:06
memberMember 117167353-Sep-15 9:06 
QuestionPrint datagridview datasource value Pin
Mekalamani28-Aug-15 0:24
memberMekalamani28-Aug-15 0:24 
QuestionMargins Pin
NFranks7-Aug-15 4:45
memberNFranks7-Aug-15 4:45 
GeneralThank you! Pin
Luis Javier Ramirez Torres21-Jun-15 21:57
memberLuis Javier Ramirez Torres21-Jun-15 21:57 
QuestionAbout In DataGridView Printing Pin
Member 1172695728-May-15 20:31
memberMember 1172695728-May-15 20:31 
Questionis it possible to adjust columns to new page? Pin
sampatrick2223-Apr-15 15:54
membersampatrick2223-Apr-15 15:54 
Questionrow coloring Pin
amin.naghdbishi1-Mar-15 7:20
memberamin.naghdbishi1-Mar-15 7:20 
AnswerRe: row coloring Pin
Chris Berger17-Mar-15 10:15
memberChris Berger17-Mar-15 10:15 
QuestionBlank Page when using printpreview dialog solved Pin
Member 1140928030-Jan-15 6:47
memberMember 1140928030-Jan-15 6:47 
AnswerRe: Blank Page when using printpreview dialog solved Pin
Member 1072757226-Mar-15 3:22
memberMember 1072757226-Mar-15 3:22 
QuestionHow to create draw footer when printer ?? Pin
Satoh Daiki27-Jan-15 17:58
memberSatoh Daiki27-Jan-15 17:58 
QuestionWhat is "arrColumnLefts" and "arrColumnWidths" please? Pin
Salisu Shaibu16-Nov-14 7:25
memberSalisu Shaibu16-Nov-14 7:25 
AnswerRe: What is "arrColumnLefts" and "arrColumnWidths" please? Pin
Member 1160775814-Apr-15 14:31
memberMember 1160775814-Apr-15 14:31 
Questionc# Pin
Salisu Shaibu15-Nov-14 8:30
memberSalisu Shaibu15-Nov-14 8:30 
QuestionHow to print 4 grids in one print document? Pin
Member 112015823-Nov-14 0:42
memberMember 112015823-Nov-14 0:42 
QuestionPrint endless when more Rows than 21 are selected Pin
Member 1062093529-Sep-14 20:30
memberMember 1062093529-Sep-14 20:30 
QuestionWorks like a charm but.. Pin
Christian Muñoz27-Aug-14 10:28
memberChristian Muñoz27-Aug-14 10:28 
QuestionBlank Page Pin
Member 1103268724-Aug-14 7:46
memberMember 1103268724-Aug-14 7:46 
GeneralThank you! Pin
lines073-Jul-14 2:22
memberlines073-Jul-14 2:22 
QuestionVery Handy Pin
Member 1083880522-May-14 22:05
memberMember 1083880522-May-14 22:05 
QuestionThank you, great Print of GridView. Pin
SBMSSOL4-May-14 2:29
memberSBMSSOL4-May-14 2:29 
QuestionPrinting of DataGridView Pin
Member 1060361428-Mar-14 12:57
memberMember 1060361428-Mar-14 12:57 
Questionhelp in code of article Pin
gjmkdyttyhujk21-Mar-14 20:39
membergjmkdyttyhujk21-Mar-14 20:39 
Questiongreat!!! Pin
thongntt19893-Mar-14 16:24
memberthongntt19893-Mar-14 16:24 
GeneralStill works like a champ Pin
Member 105774566-Feb-14 11:46
memberMember 105774566-Feb-14 11:46 
QuestionWell Done... Pin
manojmadhuranga29-Jan-14 20:41
membermanojmadhuranga29-Jan-14 20:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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 | Terms of Use | Mobile
Web04 | 2.8.170924.2 | Last Updated 31 Jul 2008
Article Copyright 2008 by Life with .NET
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid