Click here to Skip to main content
15,121,505 members
Articles / Programming Languages / C#
Article
Posted 4 Apr 2006

Stats

899.6K views
49.3K downloads
316 bookmarked

The DataGridViewPrinter Class

Rate me:
Please Sign up or sign in to vote.
4.91/5 (150 votes)
16 May 20063 min read
A printing class for the DataGridView

Sample Image - DataGridViewPrinterApplication.jpg

Introduction

The DataGridView control in .NET 2.0 is an amazing data representation control, and contains many advanced features that we could benefit from. The only thing that is not supported by this control is the printing feature. I searched the web for such a feature, but did not find anything really good, and most of the printing classes that I found were for printing a DataTable object or for printing the traditional DataGrid control. Therefore, I decided to create my own code for this feature and share it with others.

The Class Features

  • The print style is almost the same as the style of the DataGridView control:
    • the same font style for the header and other rows
    • the same foreground and background styles for the header and other rows
    • the same alternating background style for the rows
    • special font for certain rows will be considered
    • special foreground and background styles for certain rows will be considered
    • the same alignment for the columns
  • Supports multiple pages
  • The width of each column to be printed is calculated to fit all the cells (including the header cell)
  • The title at the top of the page can be specified
  • The title font and color could be specified
  • The title and the header row are repeated in each page
  • The report could be top-centered (considering the top margin of the page) on the page or be aligned to the top-left margin
  • The printing process ignores any invisible rows or columns (assuming that the user does not want them to appear)
  • If the DataGridView width is greater than the page width, then the columns with x coordinate greater than the page width will be printed into another page. This ensures that all columns will be printed (Thanks to Stephen Long)Image 2
  • Support page numbering Image 3
  • The printing process uses Graphics.MeasureString to calculate the height and width for a certain text with a specified font. This ensures the preciseness of the printing. Image 4
  • The class supports Right-to-Left fonts Image 5

The Class Constructor

C#
public DataGridViewPrinter(DataGridView aDataGridView, PrintDocument aPrintDocument,
    bool CenterOnPage, bool WithTitle, string aTitleText, Font aTitleFont,
    Color aTitleColor, bool WithPaging)
  • aDataGridView: The DataGridView control which will be printed
  • aPrintDocument: The PrintDocument to be used for printing
  • CenterOnPage: Determines if the report will be printed in the top-center of the page
  • WithTitle: Determines if the page contains a title text
  • aTitleText: The title text to be printed in each page (if WithTitle is set to true)
  • aTitleFont: The font to be used with the title text (if WithTitle is set to true)
  • aTitleColor: The color to be used with the title text (if WithTitle is set to true)
  • WithPaging: Determines if the page number will be printed

How to Use the Class

The project should have the following global objects:

C#
// The DataGridView Control which will be printed.
DataGridView MyDataGridView;
// The PrintDocument to be used for printing.
PrintDocument MyPrintDocument;
// The class that will do the printing process.
DataGridViewPrinter MyDataGridViewPrinter;

Then, use the following code:

C#
// The printing setup function
private bool SetupThePrinting()
{
    PrintDialog MyPrintDialog = new PrintDialog();
    MyPrintDialog.AllowCurrentPage = false;
    MyPrintDialog.AllowPrintToFile = false;
    MyPrintDialog.AllowSelection = false;
    MyPrintDialog.AllowSomePages = false;
    MyPrintDialog.PrintToFile = false;
    MyPrintDialog.ShowHelp = false;
    MyPrintDialog.ShowNetwork = false;

    if (MyPrintDialog.ShowDialog() != DialogResult.OK)
        return false;

    MyPrintDocument.DocumentName = "Customers Report";
    MyPrintDocument.PrinterSettings = 
                        MyPrintDialog.PrinterSettings;
    MyPrintDocument.DefaultPageSettings =
    MyPrintDialog.PrinterSettings.DefaultPageSettings;
    MyPrintDocument.DefaultPageSettings.Margins = 
                     new Margins(40, 40, 40, 40);

    if (MessageBox.Show("Do you want the report to be centered on the page",
        "InvoiceManager - Center on Page", MessageBoxButtons.YesNo,
        MessageBoxIcon.Question) == DialogResult.Yes)
        MyDataGridViewPrinter = new DataGridViewPrinter(MyDataGridView,
        MyPrintDocument, true, true, "Customers", new Font("Tahoma", 18,
        FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);
    else
        MyDataGridViewPrinter = new DataGridViewPrinter(MyDataGridView,
        MyPrintDocument, false, true, "Customers", new Font("Tahoma", 18,
        FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);

    return true;
}
C#
// The Print Button
private void btnPrint_Click(object sender, EventArgs e)
{            
    if (SetupThePrinting())
        MyPrintDocument.Print();
}
C#
// The PrintPage action for the PrintDocument control
private void MyPrintDocument_PrintPage(object sender,
    System.Drawing.Printing.PrintPageEventArgs e)
{
    bool more = MyDataGridViewPrinter.DrawDataGridView(e.Graphics);
    if (more == true)
        e.HasMorePages = true;
}
C#
// The Print Preview Button
private void btnPrintPreview_Click(object sender, EventArgs e)
{
    if (SetupThePrinting())
    {
        PrintPreviewDialog MyPrintPreviewDialog = new PrintPreviewDialog();
        MyPrintPreviewDialog.Document = MyPrintDocument;
        MyPrintPreviewDialog.ShowDialog();
    }
}

Refer to the demo project that contains the DataGridViewPrinter class (.cs file) and a simple example showing how to use it.

The DataGridViewPrinter Class Source Code

C#
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Data;
using System.Windows.Forms;

class DataGridViewPrinter
{
    // The DataGridView Control which will be printed
    private DataGridView TheDataGridView;
    // The PrintDocument to be used for printing
    private PrintDocument ThePrintDocument;
    // Determine if the report will be
    // printed in the Top-Center of the page
    private bool IsCenterOnPage;
    // Determine if the page contain title text
    private bool IsWithTitle; 
    // The title text to be printed
    // in each page (if IsWithTitle is set to true)
    private string TheTitleText;
    // The font to be used with the title
    // text (if IsWithTitle is set to true)
    private Font TheTitleFont;
    // The color to be used with the title
    // text (if IsWithTitle is set to true)
    private Color TheTitleColor;
    // Determine if paging is used
    private bool IsWithPaging;
    
    // A static parameter that keep track
    // on which Row (in the DataGridView control)
    // that should be printed
    static int CurrentRow; 

    static int PageNumber;

    private int PageWidth;
    private int PageHeight;
    private int LeftMargin;
    private int TopMargin;
    private int RightMargin;
    private int BottomMargin;

    // A parameter that keeps track
    // on the y coordinate of the page,
    // so the next object to be printed
    // will start from this y coordinate
    private float CurrentY;

    private float RowHeaderHeight;
    private List<float> RowsHeight;
    private List<float> ColumnsWidth;
    private float TheDataGridViewWidth;
        
    // Maintain a generic list to hold start/stop
    // points for the column printing
    // This will be used for wrapping
    // in situations where the DataGridView will not
    // fit on a single page
    private List<int[]> mColumnPoints;
    private List<float> mColumnPointsWidth;
    private int mColumnPoint;
        
    // The class constructor
    public DataGridViewPrinter(DataGridView aDataGridView, 
        PrintDocument aPrintDocument,
        bool CenterOnPage, bool WithTitle, 
        string aTitleText, Font aTitleFont,
        Color aTitleColor, bool WithPaging)
    {
        TheDataGridView = aDataGridView;
        ThePrintDocument = aPrintDocument;
        IsCenterOnPage = CenterOnPage;
        IsWithTitle = WithTitle;
        TheTitleText = aTitleText;
        TheTitleFont = aTitleFont;
        TheTitleColor = aTitleColor;
        IsWithPaging = WithPaging;

        PageNumber = 0;

        RowsHeight = new List<float>();
        ColumnsWidth = new List<float>();

        mColumnPoints = new List<int[]>();
        mColumnPointsWidth = new List<float>();

        // Calculating the PageWidth and the PageHeight
        if (!ThePrintDocument.DefaultPageSettings.Landscape)
        {
            PageWidth = 
              ThePrintDocument.DefaultPageSettings.PaperSize.Width;
            PageHeight = 
              ThePrintDocument.DefaultPageSettings.PaperSize.Height;
        }
        else
        {
            PageHeight = 
              ThePrintDocument.DefaultPageSettings.PaperSize.Width;
            PageWidth = 
              ThePrintDocument.DefaultPageSettings.PaperSize.Height;
        }

        // Calculating the page margins
        LeftMargin = ThePrintDocument.DefaultPageSettings.Margins.Left;
        TopMargin = ThePrintDocument.DefaultPageSettings.Margins.Top;
        RightMargin = ThePrintDocument.DefaultPageSettings.Margins.Right;
        BottomMargin = ThePrintDocument.DefaultPageSettings.Margins.Bottom;

        // First, the current row to be printed
        // is the first row in the DataGridView control
        CurrentRow = 0;
    }

    // The function that calculates
    // the height of each row (including the header row),
    // the width of each column (according
    // to the longest text in all its cells including
    // the header cell), and the whole DataGridView width
    private void Calculate(Graphics g)
    {
        if (PageNumber == 0)
        // Just calculate once
        {
            SizeF tmpSize = new SizeF();
            Font tmpFont;
            float tmpWidth;

            TheDataGridViewWidth = 0;
            for (int i = 0; i < TheDataGridView.Columns.Count; i++)
            {
                tmpFont = TheDataGridView.ColumnHeadersDefaultCellStyle.Font;
                if (tmpFont == null)
                // If there is no special HeaderFont style,
                // then use the default DataGridView font style
                    tmpFont = TheDataGridView.DefaultCellStyle.Font;

                tmpSize = g.MeasureString(
                          TheDataGridView.Columns[i].HeaderText, 
                          tmpFont);
                tmpWidth = tmpSize.Width;
                RowHeaderHeight = tmpSize.Height;

                for (int j = 0; j < TheDataGridView.Rows.Count; j++)
                {
                    tmpFont = TheDataGridView.Rows[j].DefaultCellStyle.Font;
                    if (tmpFont == null)
                    // If the there is no special font style of the
                    // CurrentRow, then use the default one associated
                    // with the DataGridView control
                        tmpFont = TheDataGridView.DefaultCellStyle.Font;

                    tmpSize = g.MeasureString("Anything", tmpFont);
                    RowsHeight.Add(tmpSize.Height);

                    tmpSize =
                        g.MeasureString(
                        TheDataGridView.Rows[j].Cells[i].
                                 EditedFormattedValue.ToString(),
                        tmpFont);
                    if (tmpSize.Width > tmpWidth)
                        tmpWidth = tmpSize.Width;
                }
                if (TheDataGridView.Columns[i].Visible)
                    TheDataGridViewWidth += tmpWidth;
                ColumnsWidth.Add(tmpWidth);
            }

            // Define the start/stop column points
            // based on the page width and
            // the DataGridView Width
            // We will use this to determine
            // the columns which are drawn on each page
            // and how wrapping will be handled
            // By default, the wrapping will occurr
            // such that the maximum number of
            // columns for a page will be determined
            int k;

            int mStartPoint = 0;
            for (k = 0; k < TheDataGridView.Columns.Count; k++)
                if (TheDataGridView.Columns[k].Visible)
                {
                    mStartPoint = k;
                    break;
                }

            int mEndPoint = TheDataGridView.Columns.Count;
            for (k = TheDataGridView.Columns.Count - 1; k >= 0; k--)
                if (TheDataGridView.Columns[k].Visible)
                {
                    mEndPoint = k + 1;
                    break;
                }

            float mTempWidth = TheDataGridViewWidth;
            float mTempPrintArea = (float)PageWidth - (float)LeftMargin -
                (float)RightMargin;
            
            // We only care about handling
            // where the total datagridview width is bigger
            // then the print area
            if (TheDataGridViewWidth > mTempPrintArea)
            {
                mTempWidth = 0.0F;
                for (k = 0; k < TheDataGridView.Columns.Count; k++)
                {
                    if (TheDataGridView.Columns[k].Visible)
                    {
                        mTempWidth += ColumnsWidth[k];
                        // If the width is bigger
                        // than the page area, then define a new
                        // column print range
                        if (mTempWidth > mTempPrintArea)
                        {
                            mTempWidth -= ColumnsWidth[k];
                            mColumnPoints.Add(new int[] { mStartPoint, mEndPoint });
                            mColumnPointsWidth.Add(mTempWidth);
                            mStartPoint = k;
                            mTempWidth = ColumnsWidth[k];
                        }
                    }
                    // Our end point is actually
                    // one index above the current index
                    mEndPoint = k + 1;
                }
            }
            // Add the last set of columns
            mColumnPoints.Add(new int[] { mStartPoint, mEndPoint });
            mColumnPointsWidth.Add(mTempWidth);
            mColumnPoint = 0;
        }
    }

    // The funtion that prints the title, page number, and the header row
    private void DrawHeader(Graphics g)
    {
        CurrentY = (float)TopMargin;

        // Printing the page number (if isWithPaging is set to true)
        if (IsWithPaging)
        {
            PageNumber++;
            string PageString = "Page " + PageNumber.ToString();

            StringFormat PageStringFormat = new StringFormat();
            PageStringFormat.Trimming = StringTrimming.Word;
            PageStringFormat.FormatFlags = StringFormatFlags.NoWrap |
                StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
            PageStringFormat.Alignment = StringAlignment.Far;

            Font PageStringFont = new Font("Tahoma", 8, FontStyle.Regular,
                GraphicsUnit.Point);

            RectangleF PageStringRectangle = 
               new RectangleF((float)LeftMargin, CurrentY,
               (float)PageWidth - (float)RightMargin - (float)LeftMargin,
               g.MeasureString(PageString, PageStringFont).Height);

            g.DrawString(PageString, PageStringFont, 
               new SolidBrush(Color.Black),
               PageStringRectangle, PageStringFormat);

            CurrentY += g.MeasureString(PageString, 
                                 PageStringFont).Height;
        }

        // Printing the title (if IsWithTitle is set to true)
        if (IsWithTitle)
        {
            StringFormat TitleFormat = new StringFormat();
            TitleFormat.Trimming = StringTrimming.Word;
            TitleFormat.FormatFlags = StringFormatFlags.NoWrap |
                StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
            if (IsCenterOnPage)
                TitleFormat.Alignment = StringAlignment.Center;
            else
                TitleFormat.Alignment = StringAlignment.Near;

            RectangleF TitleRectangle = 
                new RectangleF((float)LeftMargin, CurrentY,
                (float)PageWidth - (float)RightMargin - (float)LeftMargin,
                g.MeasureString(TheTitleText, TheTitleFont).Height);

            g.DrawString(TheTitleText, TheTitleFont, 
                new SolidBrush(TheTitleColor),
                TitleRectangle, TitleFormat);

            CurrentY += g.MeasureString(TheTitleText, TheTitleFont).Height;
        }

        // Calculating the starting x coordinate
        // that the printing process will start from
        float CurrentX = (float)LeftMargin;
        if (IsCenterOnPage)            
            CurrentX += (((float)PageWidth - (float)RightMargin - 
              (float)LeftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F;

        // Setting the HeaderFore style
        Color HeaderForeColor = 
              TheDataGridView.ColumnHeadersDefaultCellStyle.ForeColor;
        if (HeaderForeColor.IsEmpty)
        // If there is no special HeaderFore style,
        // then use the default DataGridView style
            HeaderForeColor = TheDataGridView.DefaultCellStyle.ForeColor;
        SolidBrush HeaderForeBrush = new SolidBrush(HeaderForeColor);

        // Setting the HeaderBack style
        Color HeaderBackColor = 
              TheDataGridView.ColumnHeadersDefaultCellStyle.BackColor;
        if (HeaderBackColor.IsEmpty)
        // If there is no special HeaderBack style,
        // then use the default DataGridView style
            HeaderBackColor = TheDataGridView.DefaultCellStyle.BackColor;
        SolidBrush HeaderBackBrush = new SolidBrush(HeaderBackColor);

        // Setting the LinePen that will
        // be used to draw lines and rectangles
        // (derived from the GridColor property
        // of the DataGridView control)
        Pen TheLinePen = new Pen(TheDataGridView.GridColor, 1);

        // Setting the HeaderFont style
        Font HeaderFont = TheDataGridView.ColumnHeadersDefaultCellStyle.Font;
        if (HeaderFont == null)
        // If there is no special HeaderFont style,
        // then use the default DataGridView font style
            HeaderFont = TheDataGridView.DefaultCellStyle.Font;

        // Calculating and drawing the HeaderBounds        
        RectangleF HeaderBounds = new RectangleF(CurrentX, CurrentY,
            mColumnPointsWidth[mColumnPoint], RowHeaderHeight);
        g.FillRectangle(HeaderBackBrush, HeaderBounds);

        // Setting the format that will be
        // used to print each cell of the header row
        StringFormat CellFormat = new StringFormat();
        CellFormat.Trimming = StringTrimming.Word;
        CellFormat.FormatFlags = StringFormatFlags.NoWrap |
           StringFormatFlags.LineLimit | StringFormatFlags.NoClip;

        // Printing each visible cell of the header row
        RectangleF CellBounds;
        float ColumnWidth;        
        for (int i = (int)mColumnPoints[mColumnPoint].GetValue(0);
            i < (int)mColumnPoints[mColumnPoint].GetValue(1); i++)
        {
            // If the column is not visible then ignore this iteration
            if (!TheDataGridView.Columns[i].Visible) continue; 

            ColumnWidth = ColumnsWidth[i];

            // Check the CurrentCell alignment
            // and apply it to the CellFormat
            if (TheDataGridView.ColumnHeadersDefaultCellStyle.
                       Alignment.ToString().Contains("Right"))
                CellFormat.Alignment = StringAlignment.Far;
            else if (TheDataGridView.ColumnHeadersDefaultCellStyle.
                     Alignment.ToString().Contains("Center"))
                CellFormat.Alignment = StringAlignment.Center;
            else
                CellFormat.Alignment = StringAlignment.Near;

            CellBounds = new RectangleF(CurrentX, CurrentY, 
                         ColumnWidth, RowHeaderHeight);

            // Printing the cell text
            g.DrawString(TheDataGridView.Columns[i].HeaderText, 
                         HeaderFont, HeaderForeBrush,
               CellBounds, CellFormat);

            // Drawing the cell bounds
            // Draw the cell border only if the HeaderBorderStyle is not None
            if (TheDataGridView.RowHeadersBorderStyle != 
                            DataGridViewHeaderBorderStyle.None)
                g.DrawRectangle(TheLinePen, CurrentX, CurrentY, ColumnWidth,
                    RowHeaderHeight);

            CurrentX += ColumnWidth;
        }

        CurrentY += RowHeaderHeight;
    }

    // The function that prints a bunch of rows that fit in one page
    // When it returns true, meaning that
    // there are more rows still not printed,
    // so another PagePrint action is required
    // When it returns false, meaning that all rows are printed
    // (the CureentRow parameter reaches
    // the last row of the DataGridView control)
    // and no further PagePrint action is required
    private bool DrawRows(Graphics g)
    {
        // Setting the LinePen that will be used to draw lines and rectangles
        // (derived from the GridColor property of the DataGridView control)
        Pen TheLinePen = new Pen(TheDataGridView.GridColor, 1);

        // The style parameters that will be used to print each cell
        Font RowFont;
        Color RowForeColor;
        Color RowBackColor;
        SolidBrush RowForeBrush;
        SolidBrush RowBackBrush;
        SolidBrush RowAlternatingBackBrush;

        // Setting the format that will be used to print each cell
        StringFormat CellFormat = new StringFormat();
        CellFormat.Trimming = StringTrimming.Word;
        CellFormat.FormatFlags = StringFormatFlags.NoWrap | 
                                 StringFormatFlags.LineLimit;

        // Printing each visible cell
        RectangleF RowBounds;
        float CurrentX;
        float ColumnWidth;
        while (CurrentRow < TheDataGridView.Rows.Count)
        {
            // Print the cells of the CurrentRow only if that row is visible
            if (TheDataGridView.Rows[CurrentRow].Visible)
            {
                // Setting the row font style
                RowFont = TheDataGridView.Rows[CurrentRow].DefaultCellStyle.Font;
                // If there is no special font style of the CurrentRow,
                // then use the default one associated with the DataGridView control
                if (RowFont == null)
                    RowFont = TheDataGridView.DefaultCellStyle.Font;

                // Setting the RowFore style
                RowForeColor = 
                  TheDataGridView.Rows[CurrentRow].DefaultCellStyle.ForeColor;
                // If there is no special RowFore style of the CurrentRow,
                // then use the default one associated with the DataGridView control
                if (RowForeColor.IsEmpty)
                    RowForeColor = TheDataGridView.DefaultCellStyle.ForeColor;
                RowForeBrush = new SolidBrush(RowForeColor);

                // Setting the RowBack (for even rows) and the RowAlternatingBack
                // (for odd rows) styles
                RowBackColor = 
                  TheDataGridView.Rows[CurrentRow].DefaultCellStyle.BackColor;
                // If there is no special RowBack style of the CurrentRow,
                // then use the default one associated with the DataGridView control
                if (RowBackColor.IsEmpty)
                {
                    RowBackBrush = new SolidBrush(
                          TheDataGridView.DefaultCellStyle.BackColor);
                    RowAlternatingBackBrush = new
                        SolidBrush(
                        TheDataGridView.AlternatingRowsDefaultCellStyle.BackColor);
                }
                // If there is a special RowBack style of the CurrentRow,
                // then use it for both the RowBack and the RowAlternatingBack styles
                else
                {
                    RowBackBrush = new SolidBrush(RowBackColor);
                    RowAlternatingBackBrush = new SolidBrush(RowBackColor);
                }

                // Calculating the starting x coordinate
                // that the printing process will
                // start from
                CurrentX = (float)LeftMargin;
                if (IsCenterOnPage)                    
                    CurrentX += (((float)PageWidth - (float)RightMargin -
                        (float)LeftMargin) - 
                        mColumnPointsWidth[mColumnPoint]) / 2.0F;

                // Calculating the entire CurrentRow bounds                
                RowBounds = new RectangleF(CurrentX, CurrentY,
                    mColumnPointsWidth[mColumnPoint], RowsHeight[CurrentRow]);

                // Filling the back of the CurrentRow
                if (CurrentRow % 2 == 0)
                    g.FillRectangle(RowBackBrush, RowBounds);
                else
                    g.FillRectangle(RowAlternatingBackBrush, RowBounds);

                // Printing each visible cell of the CurrentRow                
                for (int CurrentCell = (int)mColumnPoints[mColumnPoint].GetValue(0);
                    CurrentCell < (int)mColumnPoints[mColumnPoint].GetValue(1);
                    CurrentCell++)
                {
                    // If the cell belongs to invisible
                    // column, then ignore this iteration
                    if (!TheDataGridView.Columns[CurrentCell].Visible) continue;

                    // Check the CurrentCell alignment
                    // and apply it to the CellFormat
                    if (TheDataGridView.Columns[CurrentCell].DefaultCellStyle.
                            Alignment.ToString().Contains("Right"))
                        CellFormat.Alignment = StringAlignment.Far;
                    else if (TheDataGridView.Columns[CurrentCell].DefaultCellStyle.
                            Alignment.ToString().Contains("Center"))
                        CellFormat.Alignment = StringAlignment.Center;
                    else
                        CellFormat.Alignment = StringAlignment.Near;
                    
                    ColumnWidth = ColumnsWidth[CurrentCell];
                    RectangleF CellBounds = new RectangleF(CurrentX, CurrentY,
                        ColumnWidth, RowsHeight[CurrentRow]);

                    // Printing the cell text
                    g.DrawString(
                      TheDataGridView.Rows[CurrentRow].Cells[CurrentCell].
                      EditedFormattedValue.ToString(), RowFont, RowForeBrush,
                      CellBounds, CellFormat);
                    
                    // Drawing the cell bounds
                    // Draw the cell border only
                    // if the CellBorderStyle is not None
                    if (TheDataGridView.CellBorderStyle != 
                                DataGridViewCellBorderStyle.None)
                        g.DrawRectangle(TheLinePen, CurrentX, CurrentY, 
                              ColumnWidth, RowsHeight[CurrentRow]);

                    CurrentX += ColumnWidth;
                }
                CurrentY += RowsHeight[CurrentRow];

                // Checking if the CurrentY exceeds the page boundaries
                // If so, then exit the function and returning true meaning another
                // PagePrint action is required
                if ((int)CurrentY > (PageHeight - TopMargin - BottomMargin))
                {
                    CurrentRow++;
                    return true;
                }
            }
            CurrentRow++;
        }

        CurrentRow = 0;
        // Continue to print the next group of columns
        mColumnPoint++;

        if (mColumnPoint == mColumnPoints.Count)
        // Which means all columns are printed
        {
            mColumnPoint = 0;
            return false;
        }
        else
            return true;
    }

    // The method that calls all other functions
    public bool DrawDataGridView(Graphics g)
    {
        try
        {
            Calculate(g);
            DrawHeader(g);
            bool bContinue = DrawRows(g);
            return bContinue;
        }
        catch (Exception ex)
        {
            MessageBox.Show("Operation failed: " + ex.Message.ToString(),
                Application.ProductName + " - Error", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
            return false;
        }
    }
}

Problems With the Class

  • If a certain column's width is greater than the page width, then the excluded text will not be wrapped or printed in another page.
  • The class does not support image cells.

License

This article has no explicit license attached to it, but may contain usage terms in the article text or the download files themselves. If in doubt, please contact the author via the discussion board below.

A list of licenses authors might use can be found here.

Share

About the Author

Salan Alani
Software Developer
United States United States
B.Sc in Computer Engineering Dpt.
M.Sc in Software Engineering Dpt.

ASP.NET Developer
C#.NET Developer
VB.NET Developer
MS SQL Server Developer
Oracle Developer

Comments and Discussions

 
GeneralRe: Only prints blanks. Pin
sureyyan13-Sep-09 21:44
Membersureyyan13-Sep-09 21:44 
GeneralRe: Only prints blanks. Pin
Tvalone14-Sep-09 8:31
MemberTvalone14-Sep-09 8:31 
GeneralRe: Only prints blanks. Pin
CzumA14-Sep-09 22:45
MemberCzumA14-Sep-09 22:45 
GeneralRe: Only prints blanks. Pin
ivica rangelov5-Nov-09 23:43
Memberivica rangelov5-Nov-09 23:43 
GeneralRe: Only prints blanks. Pin
ELDuderino060730-Sep-11 2:31
MemberELDuderino060730-Sep-11 2:31 
GeneralWrapped Cell Not Applied in the Print Preview - It has been Fixed [modified] Pin
ponraja12-Aug-09 3:27
Memberponraja12-Aug-09 3:27 
QuestionHow to use this code in VB.net Pin
sumit_harit13-Jul-09 4:25
Membersumit_harit13-Jul-09 4:25 
GeneralVB Code with some new features Pin
Daniel Leykauf21-Jun-09 5:28
MemberDaniel Leykauf21-Jun-09 5:28 
Attached a modified VB code with some new features:

- Optional displaying of total page number
- Easier call to print or preview:

Initial call to print:
Dim prt As New DataGridPrinter(Me.DataGridView1)
With prt
.TitleForeColor = Color.Red
.TitleFont = New Font("Arial", 16, FontStyle.Bold, GraphicsUnit.Point)
.SetPageSettings() 'optional to show dialog, otherweise remove line
.Title = "Test pages ..."
.Print(PrintAction.PrintToPreview)
End With

------------------------------------------------------
'Modified class


Imports System
Imports System.Text
Imports System.Collections
Imports System.Collections.Generic
Imports System.Drawing
Imports System.Drawing.Printing
Imports System.Data
Imports System.Windows.Forms

Public Class DataGridPrinter

Private mPrt As DataGridViewPrinter
Private WithEvents mDoc As PrintDocument
Private mDgr As DataGridView
Private mPageSet As PageSettings
Private mDlgPre As PrintPreviewDialog
Private mDlgPrt As PrintDialog

#Region " Properties "
Private mTitle As String = "Title"
''' <summary>
''' Page title
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Property Title() As String
Get
Return mTitle
End Get
Set(ByVal value As String)
mTitle = value
End Set
End Property

Private mTitleFont As Font
''' <summary>
''' Font of title
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Property TitleFont() As Font
Get
Return mTitleFont
End Get
Set(ByVal value As Font)
mTitleFont = value
End Set
End Property

Private mColor As Color = Color.Black
''' <summary>
''' Title forecolor
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Property TitleForeColor() As Color
Get
Return mColor
End Get
Set(ByVal value As Color)
mColor = value
End Set
End Property

Private mShowTitle As Boolean = True
''' <summary>
''' Will title be shown?
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Property ShowTitle() As Boolean
Get
Return mShowTitle
End Get
Set(ByVal value As Boolean)
mShowTitle = value
End Set
End Property

Private mCenter As Boolean = False
''' <summary>
''' Content centered on page
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Property CenterOnPage() As Boolean
Get
Return mCenter
End Get
Set(ByVal value As Boolean)
mCenter = value
End Set
End Property

Private mPageNumber As Boolean = True
''' <summary>
''' Show page numbers
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Property ShowPageNumbers() As Boolean
Get
Return mPageNumber
End Get
Set(ByVal value As Boolean)
mPageNumber = value
End Set
End Property

Private mShowTotalNumber As Boolean = True
''' <summary>
''' Show total page numbers
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Property ShowTotalNumber() As Boolean
Get
Return mShowTotalNumber
End Get
Set(ByVal value As Boolean)
mShowTotalNumber = value
End Set
End Property

Private mPageNumberText As String = "Page"
''' <summary>
''' Displayed text: 'PAGE ...'
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Property PageNumberText() As String
Get
Return mPageNumberText
End Get
Set(ByVal value As String)
mPageNumberText = value
End Set
End Property
#End Region


Private Sub mDoc_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles mDoc.PrintPage
e.HasMorePages = mPrt.DrawDataGridView(e.Graphics)
End Sub

Public Sub New(ByVal dgr As DataGridView)
mDgr = dgr
mTitleFont = dgr.Font
End Sub

''' <summary>
''' Main sub to start printing
''' </summary>
''' <param name="Action"></param>
''' <remarks></remarks>
Public Sub Print(Optional ByVal Action As PrintAction = PrintAction.PrintToPreview)

mDoc = New PrintDocument

If Not IsNothing(mPageSet) Then
mDoc.PrinterSettings = mPageSet.PrinterSettings
mDoc.DefaultPageSettings = mPageSet.PrinterSettings.DefaultPageSettings
mDoc.DefaultPageSettings.Margins = mPageSet.Margins
End If

Select Case Action
Case PrintAction.PrintToPreview
mDlgPre = New PrintPreviewDialog
With mDlgPre
.Document = mDoc
mPrt = New DataGridPrinter.DataGridViewPrinter(mDgr, _
mDoc, CenterOnPage, ShowTitle, Title, _
TitleFont, TitleForeColor, ShowPageNumbers, _
ShowTotalNumber, PageNumberText)
If IsNothing(mPageSet) Then
mDoc.DefaultPageSettings.Margins = New Margins(40, 40, 40, 40)
End If
If Not .ShowDialog = DialogResult.OK Then
Exit Sub
End If
End With
mDlgPre = Nothing

Case PrintAction.PrintToPrinter
mDlgPrt = New PrintDialog
With mDlgPrt
.PrintToFile = False
.AllowPrintToFile = False
If Not .ShowDialog = DialogResult.OK Then Exit Sub
If IsNothing(mPageSet) Then
mDoc.PrinterSettings = .PrinterSettings
mDoc.DefaultPageSettings = .PrinterSettings.DefaultPageSettings
Else
mDoc.DefaultPageSettings.Margins = New Margins(40, 40, 40, 40)
End If
mPrt = New DataGridPrinter.DataGridViewPrinter(mDgr, _
mDoc, CenterOnPage, ShowTitle, Title, _
TitleFont, TitleForeColor, ShowPageNumbers, _
ShowTotalNumber, PageNumberText)
mDoc.Print()
End With
mDlgPrt = Nothing

Case Else
mDlgPrt = New PrintDialog
With mDlgPrt
.PrintToFile = True
.AllowPrintToFile = True
If IsNothing(mPageSet) Then
mDoc.PrinterSettings = .PrinterSettings
mDoc.DefaultPageSettings = .PrinterSettings.DefaultPageSettings
Else
mDoc.DefaultPageSettings.Margins = New Margins(40, 40, 40, 40)
End If
If Not .ShowDialog = DialogResult.OK Then Exit Sub
mPrt = New DataGridPrinter.DataGridViewPrinter(mDgr, _
mDoc, CenterOnPage, ShowTitle, Title, _
TitleFont, TitleForeColor, ShowPageNumbers, _
ShowTotalNumber, PageNumberText)
mDoc.Print()
End With
mDlgPrt = Nothing
End Select

mDoc = Nothing
mPrt = Nothing
End Sub

Public Sub SetPageSettings()
Dim dlg As New PageSetupDialog
mDoc = New PrintDocument
With dlg
.Document = mDoc
If .ShowDialog = DialogResult.OK Then
ApplyPageSettings(dlg.PageSettings)
End If
End With
End Sub

Public Sub ApplyPageSettings(ByVal Settings As PageSettings)
mPageSet = Settings
End Sub


Public Class DataGridViewPrinter
Private TheDataGridView As DataGridView
' The DataGridView Control which will be printed
Private ThePrintDocument As PrintDocument
' The PrintDocument to be used for printing
Private IsCenterOnPage As Boolean
' Determine if the report will be printed in the Top-Center of the page
Private IsWithTitle As Boolean
' Determine if the page contain title text
Private TheTitleText As String
' The title text to be printed in each page (if IsWithTitle is set to true)
Private TheTitleFont As Font
' The font to be used with the title text (if IsWithTitle is set to true)
Private TheTitleColor As Color
' The color to be used with the title text (if IsWithTitle is set to true)
Private IsWithPaging As Boolean
' Determine if paging is used
Shared CurrentRow As Integer
' A static parameter that keep track on which Row (in the DataGridView control) that should be printed
Shared PageNumber As Integer
' Temp pagenumbers for total
'Private mPages As Integer
' Total page number
Private Pages As Integer = 0

Private PageWidth As Integer
Private PageHeight As Integer
Private LeftMargin As Integer
Private TopMargin As Integer
Private RightMargin As Integer
Private BottomMargin As Integer

Private OnlyCount As Boolean

Private CurrentY As Single
' A parameter that keep track on the y coordinate of the page, so the next object to be printed will start from this y coordinate
Private RowHeaderHeight As Single
Private RowsHeight As List(Of Single)
Private ColumnsWidth As List(Of Single)
Private TheDataGridViewWidth As Single

' Maintain a generic list to hold start/stop points for the column printing
' This will be used for wrapping in situations where the DataGridView will not fit on a single page
Private mColumnPoints As List(Of Integer())
Private mColumnPointsWidth As List(Of Single)
Private mColumnPoint As Integer

' Indicator if printing starts
Private mStart As Boolean
' Show total page numbers?
Private mTotalNumber As Boolean
Private mPageNumberText As String

'Used to call printing and to calculate total number
Private Sub CalcPages()
If Not mTotalNumber Then Exit Sub
mStart = True
Pages = 0
Dim c As New Control
Dim e As Graphics = c.CreateGraphics
Do Until Not DrawDataGridView(e)
Loop
c.Dispose()
c = Nothing
CurrentRow = 0
mStart = False
End Sub

' The class constructor
Public Sub New(ByVal aDataGridView As DataGridView, _
ByVal aPrintDocument As PrintDocument, _
ByVal CenterOnPage As Boolean, _
ByVal WithTitle As Boolean, _
ByVal aTitleText As String, _
ByVal aTitleFont As Font, _
ByVal aTitleColor As Color, _
ByVal WithPaging As Boolean, _
ByVal ShowTotalNumber As Boolean, _
Optional ByVal PageNumberText As String = "Page")

TheDataGridView = aDataGridView
ThePrintDocument = aPrintDocument
IsCenterOnPage = CenterOnPage
IsWithTitle = WithTitle
TheTitleText = aTitleText
TheTitleFont = aTitleFont
TheTitleColor = aTitleColor
IsWithPaging = WithPaging
mTotalNumber = ShowTotalNumber
mPageNumberText = PageNumberText

PageNumber = 0
mStart = True

RowsHeight = New List(Of Single)()
ColumnsWidth = New List(Of Single)()

mColumnPoints = New List(Of Integer())()
mColumnPointsWidth = New List(Of Single)()

' Claculating the PageWidth and the PageHeight
If Not ThePrintDocument.DefaultPageSettings.Landscape Then
PageWidth = ThePrintDocument.DefaultPageSettings.PaperSize.Width
PageHeight = ThePrintDocument.DefaultPageSettings.PaperSize.Height
Else
PageHeight = ThePrintDocument.DefaultPageSettings.PaperSize.Width
PageWidth = ThePrintDocument.DefaultPageSettings.PaperSize.Height
End If

' Claculating the page margins
LeftMargin = ThePrintDocument.DefaultPageSettings.Margins.Left - ThePrintDocument.DefaultPageSettings.HardMarginX
TopMargin = ThePrintDocument.DefaultPageSettings.Margins.Top - ThePrintDocument.DefaultPageSettings.HardMarginY
RightMargin = ThePrintDocument.DefaultPageSettings.Margins.Right + ThePrintDocument.DefaultPageSettings.HardMarginX
BottomMargin = ThePrintDocument.DefaultPageSettings.Margins.Bottom + ThePrintDocument.DefaultPageSettings.HardMarginY

' First, the current row to be printed is the first row in the DataGridView control
CurrentRow = 0

CalcPages()
End Sub

' The function that calculate the height of each row (including the header row), the width of each column (according to the longest text in all its cells including the header cell), and the whole DataGridView width
Private Sub Calculate(ByVal g As Graphics)
If mStart Then
' Just calculate once
Dim tmpSize As New SizeF()
Dim tmpFont As Font
Dim tmpWidth As Single

TheDataGridViewWidth = 0
For i As Integer = 0 To TheDataGridView.Columns.Count - 1
tmpFont = TheDataGridView.ColumnHeadersDefaultCellStyle.Font
If tmpFont Is Nothing Then
' If there is no special HeaderFont style, then use the default DataGridView font style
tmpFont = TheDataGridView.DefaultCellStyle.Font
End If

tmpSize = g.MeasureString(TheDataGridView.Columns(i).HeaderText, tmpFont)
tmpWidth = tmpSize.Width
RowHeaderHeight = tmpSize.Height

For j As Integer = 0 To TheDataGridView.Rows.Count - 1
tmpFont = TheDataGridView.Rows(j).DefaultCellStyle.Font
If tmpFont Is Nothing Then
' If the there is no special font style of the CurrentRow, then use the default one associated with the DataGridView control
tmpFont = TheDataGridView.DefaultCellStyle.Font
End If

tmpSize = g.MeasureString("Anything", tmpFont)
RowsHeight.Add(tmpSize.Height)

tmpSize = g.MeasureString(TheDataGridView.Rows(j).Cells(i).EditedFormattedValue.ToString(), tmpFont)
If tmpSize.Width > tmpWidth Then
tmpWidth = tmpSize.Width
End If
Next
If TheDataGridView.Columns(i).Visible Then
TheDataGridViewWidth += tmpWidth
End If
ColumnsWidth.Add(tmpWidth)
Next

' Define the start/stop column points based on the page width and the DataGridView Width
' We will use this to determine the columns which are drawn on each page and how wrapping will be handled
' By default, the wrapping will occurr such that the maximum number of columns for a page will be determine
Dim k As Integer

Dim mStartPoint As Integer = 0
For k = 0 To TheDataGridView.Columns.Count - 1
If TheDataGridView.Columns(k).Visible Then
mStartPoint = k
Exit For
End If
Next

Dim mEndPoint As Integer = TheDataGridView.Columns.Count
For k = TheDataGridView.Columns.Count - 1 To 0 Step -1
If TheDataGridView.Columns(k).Visible Then
mEndPoint = k + 1
Exit For
End If
Next

Dim mTempWidth As Single = TheDataGridViewWidth
Dim mTempPrintArea As Single = CSng(PageWidth) - CSng(LeftMargin) - CSng(RightMargin)

' We only care about handling where the total datagridview width is bigger then the print area
If TheDataGridViewWidth > mTempPrintArea Then
mTempWidth = 0.0F
For k = 0 To TheDataGridView.Columns.Count - 1
If TheDataGridView.Columns(k).Visible Then
mTempWidth += ColumnsWidth(k)
' If the width is bigger than the page area, then define a new column print range
If mTempWidth > mTempPrintArea Then
mTempWidth -= ColumnsWidth(k)
mColumnPoints.Add(New Integer() {mStartPoint, mEndPoint})
mColumnPointsWidth.Add(mTempWidth)
mStartPoint = k
mTempWidth = ColumnsWidth(k)
End If
End If
' Our end point is actually one index above the current index
mEndPoint = k + 1
Next
End If
' Add the last set of columns
mColumnPoints.Add(New Integer() {mStartPoint, mEndPoint})
mColumnPointsWidth.Add(mTempWidth)
mColumnPoint = 0
mStart = False
End If
End Sub

' The funtion that print the title, page number, and the header row
Private Sub DrawHeader(ByVal g As Graphics)
CurrentY = CSng(TopMargin)
PageNumber += 1

' Printing the page number (if isWithPaging is set to true)
If IsWithPaging Then
Dim PageString As String = mPageNumberText & " " & PageNumber.ToString() & IIf(mTotalNumber, "/" & Pages, "")

Dim PageStringFormat As New StringFormat()
PageStringFormat.Trimming = StringTrimming.Word
PageStringFormat.FormatFlags = StringFormatFlags.NoWrap Or StringFormatFlags.LineLimit Or StringFormatFlags.NoClip
PageStringFormat.Alignment = StringAlignment.Far

Dim PageStringFont As New Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point)
Dim PageStringRectangle As New RectangleF(CSng(LeftMargin), CurrentY, CSng(PageWidth) - CSng(RightMargin) - CSng(LeftMargin), g.MeasureString(PageString, PageStringFont).Height)

g.DrawString(PageString, PageStringFont, New SolidBrush(Color.Black), PageStringRectangle, PageStringFormat)

CurrentY += g.MeasureString(PageString, PageStringFont).Height
End If

' Printing the title (if IsWithTitle is set to true)
If IsWithTitle Then
Dim TitleFormat As New StringFormat()
TitleFormat.Trimming = StringTrimming.Word
TitleFormat.FormatFlags = StringFormatFlags.NoWrap Or StringFormatFlags.LineLimit Or StringFormatFlags.NoClip
If IsCenterOnPage Then
TitleFormat.Alignment = StringAlignment.Center
Else
TitleFormat.Alignment = StringAlignment.Near
End If

Dim TitleRectangle As New RectangleF(CSng(LeftMargin), CurrentY, CSng(PageWidth) - CSng(RightMargin) - CSng(LeftMargin), g.MeasureString(TheTitleText, TheTitleFont).Height)

g.DrawString(TheTitleText, TheTitleFont, New SolidBrush(TheTitleColor), TitleRectangle, TitleFormat)

CurrentY += g.MeasureString(TheTitleText, TheTitleFont).Height
End If

' Calculating the starting x coordinate that the printing process will start from
Dim CurrentX As Single = CSng(LeftMargin)
If IsCenterOnPage Then
CurrentX += ((CSng(PageWidth) - CSng(RightMargin) - CSng(LeftMargin)) - mColumnPointsWidth(mColumnPoint)) / 2.0F
End If

' Setting the HeaderFore style
Dim HeaderForeColor As Color = TheDataGridView.ColumnHeadersDefaultCellStyle.ForeColor
If HeaderForeColor.IsEmpty Then
' If there is no special HeaderFore style, then use the default DataGridView style
HeaderForeColor = TheDataGridView.DefaultCellStyle.ForeColor
End If
Dim HeaderForeBrush As New SolidBrush(HeaderForeColor)

' Setting the HeaderBack style
Dim HeaderBackColor As Color = TheDataGridView.ColumnHeadersDefaultCellStyle.BackColor
If HeaderBackColor.IsEmpty Then
' If there is no special HeaderBack style, then use the default DataGridView style
HeaderBackColor = TheDataGridView.DefaultCellStyle.BackColor
End If
Dim HeaderBackBrush As New SolidBrush(HeaderBackColor)

' Setting the LinePen that will be used to draw lines and rectangles (derived from the GridColor property of the DataGridView control)
Dim TheLinePen As New Pen(TheDataGridView.GridColor, 1)

' Setting the HeaderFont style
Dim HeaderFont As Font = TheDataGridView.ColumnHeadersDefaultCellStyle.Font
If HeaderFont Is Nothing Then
' If there is no special HeaderFont style, then use the default DataGridView font style
HeaderFont = TheDataGridView.DefaultCellStyle.Font
End If

' Calculating and drawing the HeaderBounds
Dim HeaderBounds As New RectangleF(CurrentX, CurrentY, mColumnPointsWidth(mColumnPoint), RowHeaderHeight)
g.FillRectangle(HeaderBackBrush, HeaderBounds)

' Setting the format that will be used to print each cell of the header row
Dim CellFormat As New StringFormat()
CellFormat.Trimming = StringTrimming.Word
CellFormat.FormatFlags = StringFormatFlags.NoWrap Or StringFormatFlags.LineLimit Or StringFormatFlags.NoClip

' Printing each visible cell of the header row
Dim CellBounds As RectangleF
Dim ColumnWidth As Single
For i As Integer = CInt(mColumnPoints(mColumnPoint).GetValue(0)) To CInt(mColumnPoints(mColumnPoint).GetValue(1)) - 1
If Not TheDataGridView.Columns(i).Visible Then
Continue For
End If
' If the column is not visible then ignore this iteration
ColumnWidth = ColumnsWidth(i)

' Check the CurrentCell alignment and apply it to the CellFormat
If TheDataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Right") Then
CellFormat.Alignment = StringAlignment.Far
ElseIf TheDataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Center") Then
CellFormat.Alignment = StringAlignment.Center
Else
CellFormat.Alignment = StringAlignment.Near
End If

CellBounds = New RectangleF(CurrentX, CurrentY, ColumnWidth, RowHeaderHeight)

' Printing the cell text
g.DrawString(TheDataGridView.Columns(i).HeaderText, HeaderFont, HeaderForeBrush, CellBounds, CellFormat)

' Drawing the cell bounds
If TheDataGridView.RowHeadersBorderStyle <> DataGridViewHeaderBorderStyle.None Then
' Draw the cell border only if the HeaderBorderStyle is not None
g.DrawRectangle(TheLinePen, CurrentX, CurrentY, ColumnWidth, RowHeaderHeight)
End If

CurrentX += ColumnWidth
Next

CurrentY += RowHeaderHeight
End Sub

' The function that print a bunch of rows that fit in one page
' When it returns true, meaning that there are more rows still not printed, so another PagePrint action is required
' When it returns false, meaning that all rows are printed (the CureentRow parameter reaches the last row of the DataGridView control) and no further PagePrint action is required
Private Function DrawRows(ByVal g As Graphics) As Boolean

' Setting the LinePen that will be used to draw lines and rectangles (derived from the GridColor property of the DataGridView control)
Dim TheLinePen As New Pen(TheDataGridView.GridColor, 1)

' The style paramters that will be used to print each cell
Dim RowFont As Font
Dim RowForeColor As Color
Dim RowBackColor As Color
Dim RowForeBrush As SolidBrush
Dim RowBackBrush As SolidBrush
Dim RowAlternatingBackBrush As SolidBrush

' Setting the format that will be used to print each cell
Dim CellFormat As New StringFormat()
CellFormat.Trimming = StringTrimming.Word
CellFormat.FormatFlags = StringFormatFlags.NoWrap Or StringFormatFlags.LineLimit

' Printing each visible cell
Dim RowBounds As RectangleF
Dim CurrentX As Single
Dim ColumnWidth As Single
While CurrentRow < TheDataGridView.Rows.Count
If TheDataGridView.Rows(CurrentRow).Visible Then
' Print the cells of the CurrentRow only if that row is visible
' Setting the row font style
RowFont = TheDataGridView.Rows(CurrentRow).DefaultCellStyle.Font
If RowFont Is Nothing Then
' If the there is no special font style of the CurrentRow, then use the default one associated with the DataGridView control
RowFont = TheDataGridView.DefaultCellStyle.Font
End If

' Setting the RowFore style
RowForeColor = TheDataGridView.Rows(CurrentRow).DefaultCellStyle.ForeColor
If RowForeColor.IsEmpty Then
' If the there is no special RowFore style of the CurrentRow, then use the default one associated with the DataGridView control
RowForeColor = TheDataGridView.DefaultCellStyle.ForeColor
End If
RowForeBrush = New SolidBrush(RowForeColor)

' Setting the RowBack (for even rows) and the RowAlternatingBack (for odd rows) styles
RowBackColor = TheDataGridView.Rows(CurrentRow).DefaultCellStyle.BackColor
If RowBackColor.IsEmpty Then
' If the there is no special RowBack style of the CurrentRow, then use the default one associated with the DataGridView control
RowBackBrush = New SolidBrush(TheDataGridView.DefaultCellStyle.BackColor)
RowAlternatingBackBrush = New SolidBrush(TheDataGridView.AlternatingRowsDefaultCellStyle.BackColor)
Else
' If the there is a special RowBack style of the CurrentRow, then use it for both the RowBack and the RowAlternatingBack styles
RowBackBrush = New SolidBrush(RowBackColor)
RowAlternatingBackBrush = New SolidBrush(RowBackColor)
End If

' Calculating the starting x coordinate that the printing process will start from
CurrentX = CSng(LeftMargin)
If IsCenterOnPage Then
CurrentX += ((CSng(PageWidth) - CSng(RightMargin) - CSng(LeftMargin)) - mColumnPointsWidth(mColumnPoint)) / 2.0F
End If

' Calculating the entire CurrentRow bounds
RowBounds = New RectangleF(CurrentX, CurrentY, mColumnPointsWidth(mColumnPoint), RowsHeight(CurrentRow))

' Filling the back of the CurrentRow
If CurrentRow Mod 2 = 0 Then
g.FillRectangle(RowBackBrush, RowBounds)
Else
g.FillRectangle(RowAlternatingBackBrush, RowBounds)
End If

' Printing each visible cell of the CurrentRow
For CurrentCell As Integer = CInt(mColumnPoints(mColumnPoint).GetValue(0)) To CInt(mColumnPoints(mColumnPoint).GetValue(1)) - 1
If Not TheDataGridView.Columns(CurrentCell).Visible Then
Continue For
End If
' If the cell is belong to invisible column, then ignore this iteration
' Check the CurrentCell alignment and apply it to the CellFormat
If TheDataGridView.Columns(CurrentCell).DefaultCellStyle.Alignment.ToString().Contains("Right") Then
CellFormat.Alignment = StringAlignment.Far
ElseIf TheDataGridView.Columns(CurrentCell).DefaultCellStyle.Alignment.ToString().Contains("Center") Then
CellFormat.Alignment = StringAlignment.Center
Else
CellFormat.Alignment = StringAlignment.Near
End If

ColumnWidth = ColumnsWidth(CurrentCell)
Dim CellBounds As New RectangleF(CurrentX, CurrentY, ColumnWidth, RowsHeight(CurrentRow))

' Printing the cell text
g.DrawString(TheDataGridView.Rows(CurrentRow).Cells(CurrentCell).EditedFormattedValue.ToString(), RowFont, RowForeBrush, CellBounds, CellFormat)

' Drawing the cell bounds
If TheDataGridView.CellBorderStyle <> DataGridViewCellBorderStyle.None Then
' Draw the cell border only if the CellBorderStyle is not None
g.DrawRectangle(TheLinePen, CurrentX, CurrentY, ColumnWidth, RowsHeight(CurrentRow))
End If

CurrentX += ColumnWidth
Next
CurrentY += RowsHeight(CurrentRow)

' Checking if the CurrentY is exceeds the page boundries
' If so then exit the function and returning true meaning another PagePrint action is required
If CInt(CurrentY) > (PageHeight - TopMargin - BottomMargin) Then
CurrentRow += 1
Return True
End If
End If
CurrentRow += 1
End While

CurrentRow = 0
mColumnPoint += 1
' Continue to print the next group of columns
If mColumnPoint = mColumnPoints.Count Then
' Which means all columns are printed
mColumnPoint = 0
If Pages < PageNumber Then Pages = PageNumber
PageNumber = 0
mStart = False
Return False
Else
Return True
End If
End Function


' The method that calls all other functions
Public Function DrawDataGridView(ByVal g As Graphics) As Boolean
Try
Calculate(g)
DrawHeader(g)
Dim bContinue As Boolean = DrawRows(g)
Return bContinue
Catch ex As Exception
MessageBox.Show("Operation failed: " & ex.Message.ToString(), Application.ProductName & " - Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
Return False
End Try
End Function
End Class

End Class
GeneralRe: VB Code with some new features Pin
Mahbub732-Jul-09 16:48
MemberMahbub732-Jul-09 16:48 
GeneralRe: VB Code with some new features Pin
Jake F24-Apr-10 7:00
MemberJake F24-Apr-10 7:00 
GeneralRe: VB Code with some new features Pin
Duane19588-Nov-10 20:05
MemberDuane19588-Nov-10 20:05 
GeneralFitToPage Pin
PrgMaster12-Jun-09 23:01
MemberPrgMaster12-Jun-09 23:01 
GeneralSmall Fix with Margins Pin
Danny Cohen12-Jun-09 10:36
MemberDanny Cohen12-Jun-09 10:36 
GeneralImpresion de filas y columnas Pin
pintamono2-Jun-09 12:35
Memberpintamono2-Jun-09 12:35 
QuestionCell with many line? Pin
billybui18-May-09 8:22
Memberbillybui18-May-09 8:22 
AnswerRe: Cell with many line? Pin
Scotty Mac20-May-09 5:37
MemberScotty Mac20-May-09 5:37 
GeneralRe: Cell with many line? Pin
symeramon21-Jul-11 22:52
Membersymeramon21-Jul-11 22:52 
QuestionCan anyone post the latest DatagridViewPrinter class (with Image support) Pin
Scotty Mac1-May-09 8:42
MemberScotty Mac1-May-09 8:42 
GeneralAmazing! thanks a lot. [modified] Pin
Pipirinberto30-Apr-09 21:27
MemberPipirinberto30-Apr-09 21:27 
GeneralImprimir otras cabeceras Pin
pintamono29-Apr-09 5:58
Memberpintamono29-Apr-09 5:58 
GeneralSupport for ComboBox and CheckBox Columns Pin
Jehanzeb27-Apr-09 21:53
MemberJehanzeb27-Apr-09 21:53 
GeneralRe: Support for ComboBox and CheckBox Columns [modified] Pin
Gief7-May-09 4:41
MemberGief7-May-09 4:41 
GeneralRe: Support for ComboBox and CheckBox Columns Pin
SinCity200019-Oct-09 23:19
MemberSinCity200019-Oct-09 23:19 
GeneralMultiple pages (without page numbers) issue [modified] Pin
packe10024-Apr-09 4:37
Memberpacke10024-Apr-09 4:37 
GeneralRe: Multiple pages (without page numbers) issue Pin
pintamono29-Apr-09 5:45
Memberpintamono29-Apr-09 5:45 

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.