Click here to Skip to main content
14,488,726 members

Printing a DataGridView with C#

Cnira asked:

Open original thread
I am generating a report into a dataGridView component and want to print it out. I found an article on this site that had a DataGridViewTestApplication which I downloaded and compiled. The application worked well. I copied and pasted the functions into my application which also had a dataGridView1 conponent on the form. The code follows:
 private void view_all()
 {
     Cursor.Current = Cursors.WaitCursor;
     SqlConnection sqlConnection = null;
     SqlCommand sqlCommand = null;
     SqlDataReader sqlReader = null;

     try
     {
         string strQuery = "SELECT Name, Telephony, RtGide, Code, Acct, AirDir FROM APRL.dbo.Patchdata where Code like 'b%'";
         string datasource = "Dave-HP\\SQLEXPRESS";
         SqlConnectionStringBuilder bu = new SqlConnectionStringBuilder();
         bu.DataSource = @datasource;
         bu.IntegratedSecurity = false; // Sql Server Authentification
         bu.UserID = "Dave";
         bu.Password = "FunFern";

         MSQLcon.ConnectionString = bu.ConnectionString;
         //     sqlConnection = new SqlConnection(strConnectionString);
         MSQLcon.Open();
         sqlCommand = new SqlCommand(strQuery, MSQLcon);
         sqlReader = sqlCommand.ExecuteReader();
         while (sqlReader.Read())
         {
             object[] row = { sqlReader[0], sqlReader[1], sqlReader[2], sqlReader[3], sqlReader[4], sqlReader[5] };
             dataGridView1.Rows.Add(row);
         }
     }
     catch (Exception exc)
     {
         MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
     finally
     {
         Cursor.Current = Cursors.Default;
         MSQLcon.Close();
         if (sqlReader != null)
         {
             sqlReader.Dispose();
             sqlReader = null;
         }
         if (sqlCommand != null)
         {
             sqlCommand.Dispose();
             sqlCommand = null;
         }
     }
 }
 #endregion

 #region Print Button Click Event
 /// <summary>
 /// Handles the print button click event
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>

 private void aVSRoutingGdToolStripMenuItem_Click(object sender, EventArgs e)
 {
     view_all();
     //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();
           }

     //Open the print preview dialog
/*     PrintPreviewDialog objPPdialog = new PrintPreviewDialog();
     objPPdialog.Document = printDocument1;
     printDocument1.DefaultPageSettings.Landscape = true;
     objPPdialog.ShowDialog();*/
 }
 #endregion

 #region Begin Print Event Handler
 /// <summary>
 /// Handles the begin print event of print document
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 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;
         iRow = 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

 #region Print Page Event
 /// <summary>
 /// Handles the print page event of print document
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 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 headres
                 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 allo 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

The viewall function fills the dataGridView with the proper data and this works fine. The void aVSRoutingGdToolStripMenuItem_Click functions is called from a menu option and first calls the viewall function to populate the data grid. From there on the code is right from the test program which works. However all I get are blank pages. I have a printDocument1 on my form. I think the printDocument does not know where to get the data from but I can't find out how to make this happen. Any help would be greatly appreciated.

Thanks!
Dave Daley
Tags: C#, printing, DataGridView

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the The Code Project Open License (CPOL).




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100