Click here to Skip to main content
Email Password   helpLost your password?

UML Design

Sample Image

Preview

Sample Image

Introduction

The DataGrid control is one of the worst things to work with, yet very needed. The real problem about this control is printing the grid. This class supports RightToLeft printing, colored and aligned grid printing...

Background

I had to do a project that supports RightToLeft grid printing, but all the printing classes I found just didn't do the job. So, I made a new one...

Implementation

The main class is PrinterClass, it does the actual print. Grid is a class holding the DataGrid data, it's made of Cells and Headers. Cell represents a single cell in a grid with Location, Font Alignment etc. Header represents a single header cell (inherits Cell).

Using the code

Grid Creation

public Grid(DataGrid TheGrid)
{
    try
    {
        //get the Data in the grid

        DataTable TableGrid = (DataTable)TheGrid.DataSource;

        //set number of rows

        rows = TableGrid.Rows.Count;

        //set number of columns

        //first check if the grid has tablestyle and columnstyle


        CreateColumnStyles(TheGrid,TableGrid);

        if (TheGrid.TableStyles[TableGrid.TableName].GridColumnStyles.Count>0)
            columns = 
              TheGrid.TableStyles[TableGrid.TableName].GridColumnStyles.Count;

        //init number of columns to headers

        Headers = new Header[Columns];

        SetHeaders(TheGrid,TableGrid);

        Cells = new Cell[Rows,Columns];

        //Copy Cells

        for (int i=0;i<Rows;i++)
        {
            for (int j=0;j<Columns;j++)
            {
                Cells[i,j] = new Cell(i, j, TheGrid.Font, 
                   TheGrid.GetCellBounds(i,j), TheGrid[i,j].ToString());
            }
        }

        //define grid colors

        SetColors(TheGrid);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
}

Grid Printing

private void PrintDataGrid(Graphics g)
{
    StringFormat sf = new StringFormat();

    //if we want to print the grid right to left

    if (bRightToLeft)
    {
        CurrentX = PrintDoc.DefaultPageSettings.PaperSize.Width - 
        PrintDoc.DefaultPageSettings.Margins.Right;

        sf.FormatFlags = StringFormatFlags.DirectionRightToLeft;
    }
    else
    {
        CurrentX = PrintDoc.DefaultPageSettings.Margins.Left;
    }

    for (int i=0;i<PrintGrid.Rows;i++)
    {
        for (int j=0;j<PrintGrid.Columns;j++)
        {
            //set cell alignment

            switch (PrintGrid[i,j].Alignment)
            {
                    //left

                case HorizontalAlignment.Left:
                    sf.Alignment = StringAlignment.Near;
                    break;

                    //center

                case HorizontalAlignment.Center:
                    sf.Alignment = StringAlignment.Center;
                    break;

                    //right

                case HorizontalAlignment.Right:
                    sf.Alignment = StringAlignment.Far;
                    break;
            }

            //advance X according to order

            if (bRightToLeft)
            {
                //draw the cell bounds (lines)

                g.DrawRectangle(Pens.Black,CurrentX - PrintGrid[i,j].Width,
                CurrentY,PrintGrid[i,j].Width,PrintGrid[i,j].Height);

                //draw the cell text

                g.DrawString(PrintGrid[i,j].Text,
                   PrintGrid[i,j].Font,Brushes.Black,
                   new RectangleF(CurrentX - PrintGrid[i,j].Width, 
                   CurrentY, PrintGrid[i,j].Width,
                   PrintGrid[i,j].Height),sf);

                //next cell

                CurrentX -=PrintGrid[i,j].Width;

            }
            else
            {
                //draw the cell bounds (lines)

                g.DrawRectangle(Pens.Black ,CurrentX,CurrentY, 
                     PrintGrid[i,j].Width,PrintGrid[i,j].Height);

                //draw the cell text

                //Draw text by alignment

                    
                g.DrawString(PrintGrid[i,j].Text,PrintGrid[i,j].Font, 
                     Brushes.Black, new RectangleF(CurrentX,CurrentY, 
                     PrintGrid[i,j].Width,PrintGrid[i,j].Height),sf);

                //next cell

                CurrentX +=PrintGrid[i,j].Width;
            }

        }

        //reset to beginning

        if (bRightToLeft)
        {
            //right align

            CurrentX = PrintDoc.DefaultPageSettings.PaperSize.Width - 
                       PrintDoc.DefaultPageSettings.Margins.Right;
        }
        else
        {
            //left align

            CurrentX = PrintDoc.DefaultPageSettings.Margins.Left;
        }

        //advance to next row

        CurrentY = CurrentY + PrintGrid[i,0].Height;
    }
}

Current Todo:

  1. Fix - When grid is empty, header is not printed well.
  2. When grid is lager than the WIDTH of the page, continue to next.

Other DataGrid Printing Classes

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralMy vote of 1
Syed Javed
19:53 11 Jan '10  
poor
Generalexcellent + small thing
xor.be
0:37 15 Nov '07  
Excellent code, really very nice. Smile

However,when you make landscape default you need to declare this as pdocument is made.
otherwise you need to close the preview window and open it again.

otherwise truly very nice Smile
Generalinvoice datagrid printing?
geee
16:56 27 Jun '07  
Thank you for this article, it was very helpful!
My original invoice program did look like that- a simple data grid and i was able to print it.

However, now I have need for another table printing that should look something like this:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Qty Item Desc UnitPrice TotalPrice
================================================================
2 Pcs Item # 001 $1.00 $2.00 First Item <--- new data PO # 111 <--- new data
4 Pcs Item # 002 $1.00 $4.00 Second Item <--- new data
PO # 111 <--- new data
Note: PO # 111 is so and so and so. <--- new data ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Obviously, it's not just a simple datagrid table anymore with the new data lines... what can you suggest i use for this particular scenario? Confused Confused can i still use my old code with the datagrid printing, and tweak it in some way to allow this kind of printing? Confused

Help!! Any suggestions would be highly appreciated! Thanks!!! Smile
GeneralRe: invoice datagrid printing?
nashcontrol
22:44 27 Jun '07  
hello, thank you for you feedback!

If I understand correctly, the new data is inside the grid, so there should not be a problem creating a high cell to contain all the data:

|------------------------------------------------------|
|Qty Item Desc UnitPrice TotalPrice |
|------------------------------------------------------|
| 2 pcs Item #001 $1.0 $2.0 |
| First Item |
| PO# 111 |
|------------------------------------------------------|
| 4 pcs Item #002 $1.0 $4.0 |
| Second Item |
| PO# 111 |
|------------------------------------------------------|

Note: PO # 111 is so and so and so. <---------------- Printed as page footer.


good day,
Alex.

GeneralRe: invoice datagrid printing?
geee
22:54 27 Jun '07  
actually, it looks more like this:

|------------------------------------------------------|
|Qty | Item Desc | UnitPrice | TotalPrice |
|------------------------------------------------------|
| 2 pcs | Item #001 | $1.0 | $2.0 |
| |First Item | | |
| |PO# 111 | | |
|------------------------------------------------------|
| 4 pcs | Item #002 | $1.0 | $4.0 |
| |Second Item | | |
| |PO# 111 | | |
|------------------------------------------------------|
Note: PO # 111 is so and so and so. <---------------- Printed as page footer.
GeneralPreview Shows Empty Page
scptech
6:38 5 May '07  
I am trying to use the code depicted here without any modification, the sample works just fine, but for some reason in my app the print preview dialog just shows an empty page.
The datagrid I am trying to print contains 5 rows.

Thanks in advance for any suggestions.
GeneralRe: Preview Shows Empty Page
nashcontrol
12:34 5 May '07  
it's all about styles.. If I remember you need to setup a default columnstyle.
Questionasp.net
H.Riazi
22:14 3 Dec '06  
is there something similar for asp.net?


thanks
Riazi
GeneralDataGridColumnStyles Problem
clueless23
22:24 26 Nov '06  
Hi,

I've been facing a problem with printing and printpreview the datagrid.. the problem is i have more than one gridcolumnstyle.. i added a label to the grid and when trying to printpreview it gives object reference not set to an instance of an object when it reaches the label column.. any help plz.

M.K

GeneralPrintings cell values formatted like in datagrid
Senol Akbulak
5:41 28 Jul '06  
Hi;

Thank you for your article and demo. It is very usefull. I used it and I changed it as this to printings cell values formatted like in datagrid;

I added a function like this:
private string GetFormatString(DataGrid TheGrid, DataTable TableGrid, int i, int j)
{
// check column is TextBox
if( TheGrid.TableStyles[TableGrid.TableName].GridColumnStyles[j] is DataGridTextBoxColumn )
return ((DataGridTextBoxColumn)TheGrid.TableStyles[TableGrid.TableName].GridColumnStyles[j]).Format;

return "";
}

And I changed this line in "public Grid(DataGrid TheGrid)"
Cells[i,j] = new Cell(i,j,TheGrid.Font,TheGrid.TableStyles[TableGrid.TableName].GridColumnStyles[j].Alignment,TheGrid.GetCellBounds(i,j), TheGrid[i, j]);

like this:
Cells[i,j] = new Cell(i,j,TheGrid.Font,TheGrid.TableStyles[TableGrid.TableName].GridColumnStyles[j].Alignment,TheGrid.GetCellBounds(i,j), String.Format("{0:"+ GetFormatString(TheGrid, TableGrid, i,j) +"}", TheGrid[i, j]));


I hope this will useful for you.


Senol Akbulak
QuestionProblem in print preview [modified]
v_sadeghpoor
14:07 14 Jun '06  
when datagrid have one row print preview has a problem.
why?
Please help me.

vahid

-- modified at 23:56 Friday 16th June, 2006
GeneralGrid Column Styles does not work
project_manager
1:14 14 Jun '06  
Carrying out further testing revealed that Grid Column Styles does not print at all. I tried to define custom data format for a column of type date time. At the time of printing, the date was printed in the default format

Can any one give any hint how to teckle this problem
GeneralNull text does not print
project_manager
20:52 13 Jun '06  
When a value in a cell is null and datagrid shows the null text like "Not Available" on the screen, the print shows an empty cell. Any solution ? (I am using table styles and grid column styles for setting null text)
Generalfit the datagrid
Trimix
16:29 28 Feb '06  
As I can fit the Datagrid so that the wide one fits in the leaf when printing it.
I have already put the pagina in landscape and follows without fitting all the columns.
GeneralI don't understand
nashcontrol
11:22 9 Mar '06  
I'm now working on an updated version where grids that are WIDER than a page are printed in the same way that pages that are LONGER are.
GeneralConversion to DataGridView
Nice Life
3:12 23 Feb '06  
Hi I have jsut conveted your code to the new DataGridView (DOT Net 2.0).
It works but needs some improvements.
Let me know if you are interested.

Have a nice life!!

-- modified at 8:12 Thursday 23rd February, 2006
GeneralRe: Conversion to DataGridView
Pink Floyd
11:17 14 Mar '06  
I AM interested Blush )

Would you mind?

Thx.
GeneralRe: Conversion to DataGridView
lilyminako
16:08 14 Mar '06  
i'm interest too, can u send me the coding at lilyminako@yahoo.com? I been trying to do it these few days but it didnt work...tq
GeneralRe: Conversion to DataGridView
Djeez
23:47 14 Mar '06  

I am interested too!

Thanks!

Emile.
GeneralRe: Conversion to DataGridView
mariadelapaz
10:40 27 Mar '06  
I am interesed!!!
GeneralRe: Conversion to DataGridView
Waruna Rajapakse
0:45 6 Jun '06  
Hi

I tried to do the same. Please send me the code if you don't mind.

Thanks
GeneralRe: Conversion to DataGridView
karan_23_j
20:54 11 Jun '06  
Hi Waruna,
Did u get the gode of this link. If yes then plz send it to me...

Thanks in Advance
Kiran

kiran
GeneralRe: Conversion to DataGridView
karan_23_j
20:48 11 Jun '06  
Hi,
I am also interested. Please send it to kiran_juikar@rediffmail.com

Thanks in Advance
Kiran Juikar

kiranj
GeneralRe: Conversion to DataGridView
Nice Life
5:58 13 Jul '06  
See http://www.codeproject.com/csharp/datagridviewprinter.asp[^].
This is much better!

Have a nice life!!
GeneralActual print doesn't how data grid
yarowave
16:34 12 Feb '06  
Hi,

DataGrid Printing Class works very good but whenever I click "Preview" then
click print it doesn't print at all.

Does anyone know how to fix it?

Thanks


Last Updated 27 Feb 2006 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010