# VBForums CodeBank > CodeBank - Visual Basic .NET >  DataGridPrinter - A class to print data grid in a nicely formatted way

## Merrion

The DataGridPrinter is a class that you can add to your applications to print (or preview) a data grid (or DataGridView) in a nciely formatted way.

The class allows you to control settings such as the header height, footer height, header font, grid font, footer font, grid line colour, header border colour, inter section spacing and so on.

The class takes care of putting the grid headings at the top of each page and generating a new page if the grid rows exceed one page etc.

Any comments or suggestions?

----------


## Merrion

I have submitted an article explaining the what and how of this class here

----------


## dinosaur_uk

I have used this, and this is fantastic....

but can we print in landscape?

----------


## Merrion

Yes - if you change the page layout (in print preview) then the columns and rows get recalculated to fit the page 'automatically'...

New version (updated with the article) supports background colours for the grid elements.

Am working on some more defect fixes and enhancements and will post the next release on this thread.

----------


## Merrion

New version - now has a property "PagesAcross" which allows you to overflow the grid across more than one page across...(users of excel know all about this functionality)

----------


## Merrion

*Option Strict* version attached.

(and it also prints all columns on the one page....  :Blush:  )

----------


## skea

Nice Sample Merrion.
How could this work under Datagridview. I have tried to convert everything named datagrid to datagridview.The page setup works fine, but the print gives me errors in the functions
getColumnHeadingText(),MappedColumnToBaseColumn
Over datagrid's tablestyles and gridcolumnstyles

----------


## Merrion

It will need to be rewritten to work for DataGridView which I will add to the list to do - I find it difficult to keep up with all the new tricks    :Blush:

----------


## skea

Here is a link to print a datagridview, but i have so far failed to convert it into vb.net.
Will some one try it out!
http://www.codeproject.com/csharp/da...iewprinter.asp

----------


## skea

Thanks to Berthold Simon, who converted the C# code.

----------


## am_binu

Thank You Merrion for the DataGridPrinter Class. How can we hide the GridLines.

Regards,
Binu

----------


## Merrion

To hide the grid lines set .Gridpen = New Pen(Color.Transparent)

----------


## am_binu

Sir,

Thank you for replying me. I am a beginner for vb.net. Pls tell me how to set the column width in DatagridPrinter.

Regards,
Binu

----------


## Merrion

Column width is proportional to the column widths on the source datagrid control...

----------


## am_binu

Sir,

The DataGridPrinter Very much helped me in my work.

In DataGridPrinter the Column width is adjusting with the Page width. So the Column Data is Printing like 'Customer N...'. Pls help me to avoid this.

----------


## Merrion

Column width is in the same proportions as the source data grid - if you make the column wider on the source grid it becomes wider on the print/preview grid.

Column width is proportional to the .pagesAcross number - the more pages across your grid is set to, the wider each column can be made.

So - increase your pages across setting and/or alter the column widths in the source data grid.

----------


## simonalexander2005

I downloaded the file from the post with: 


> Thanks to Berthold Simon, who converted the C# code.


.

how do i use this in my project? i have a datagridview and a button. What do i need to do so that when the button is pressed the datagridview is printed? i.e how do i use what i just downloaded?

----------


## am_binu

See the below article for a clear idea.

http://www.thecodeproject.com/userit...ridPrinter.asp

----------


## simonalexander2005

broken link...

----------


## simonalexander2005

am i doing this right?:

1. download the zip file
2. add the .vb file to my project
3. use code 
VB Code:
Imports PRECIS.DataGridViewPrinter
 to import the class to the form im using it in
4. put source code from readme into project:


VB Code:
Private Function SetupThePrinting() As Boolean
        Dim MyPrintDialog As PrintDialog = New PrintDialog()
         MyPrintDialog.AllowCurrentPage = False
        MyPrintDialog.AllowPrintToFile = False
        MyPrintDialog.AllowSelection = False
        MyPrintDialog.AllowSomePages = True
        MyPrintDialog.PrintToFile = False
        MyPrintDialog.ShowHelp = False
        MyPrintDialog.ShowNetwork = False
         If MyPrintDialog.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then 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 then
           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)
       end if
        Return True
    End Function
     Private Sub MyPrintDocument_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles MyPrintDocument.PrintPage
        Dim more As Boolean
         Try
            more = MyDataGridViewPrinter.DrawDataGridView(e.Graphics)
            If more Then e.HasMorePages = True
        Catch Ex As Exception
            MessageBox.Show(Ex.Message & vbCrLf & Ex.StackTrace, MyConstants.CaptionFehler, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
     ' The Print Preview Button
    Private Sub btnPrintPreview_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrintPreview.Click
        If SetupThePrinting() Then
            Dim MyPrintPreviewDialog As PrintPreviewDialog = New PrintPreviewDialog()
            MyPrintPreviewDialog.Document = MyPrintDocument
            MyPrintPreviewDialog.ShowDialog()
        End If
    End Sub
     ' The Print Button
    Private Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
    if SetupThePrinting() then MyPrintDocument.Print
    end SUb

If this is right, i am getting several errors.
most say that  MyPrintDocument and MyDataGridViewPrinter are not declared, so i have put     

VB Code:
Dim MyPrintDocument As PrintDocument
    Dim MyDataGridViewPrinter As DataGridViewPrinter
at the top of the form. is this correct?

also, in the line   
VB Code:
MessageBox.Show(Ex.Message & vbCrLf & Ex.StackTrace, MyConstants.CaptionFehler, MessageBoxButtons.OK, MessageBoxIcon.Error)
, i am getting the error that MyConstants is not declared...

I am also getting Error	1	Handles clause requires a WithEvents variable defined in the containing type or one of its base types., relating to the line 
VB Code:
Private Sub MyPrintDocument_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles MyPrintDocument.PrintPage
 , and the MyPrintDocument from	MyPrintDocument.PrintPage is underlined...

any help on these would be greatfully recieved, or, if i am not doing this right, the correct way would also be helpful. ta.

----------


## am_binu

http://www.codeproject.com/vb/net/datagridprinter.asp  :Alien Frog:

----------


## simonalexander2005

thats a totally different piece of coding, and it's for datagrids, not datagridviews - i'm using vb 200*5*...

----------


## maged

very powerful 

thank you , i will sure rate u for it   :Big Grin:

----------


## am_binu

If GridPrinter Is Nothing Then
                GridPrinter = New DataGridPrinter(Me.dgReport)
            End If
            With (GridPrinter)
                .HeaderText = "Stock Report"
                .HeaderHeightPercent = 5
                .FooterHeightPercent = 0
                .HeaderPen = New Pen(Color.Transparent)
                .GridPen = New Pen(Color.Black)
            End With

            With Me.PrintPreviewDialog1
                .Document = GridPrinter.PrintDocument
                If .ShowDialog = DialogResult.OK Then
                    GridPrinter.Print()
                End If
            End With


It Shows Following Exception in the Line "If .ShowDialog = DialogResult.OK Then"

************** Exception Text **************
System.InvalidCastException: Specified cast is not valid.
   at System.Windows.Forms.PrintPreviewControl.CalculatePageInfo()
   at System.Windows.Forms.Control.InvokeMarshaledCallbacks()

Pls tell me how to solve this Problem.

----------


## maged

i had also issues when i try to print datagird with custom column styles.

it doesnt print and raises an exception , i dont have time to study well though

----------


## Merrion

You need to put a breakpoint in the control's *PrintPage* event and step through what it is doing as the error is occuring there somewhere....let me know when you find the line that is the underlying cause of the error.

----------


## am_binu

Sir,
Its not showing the print preview also. but it works in my last finished project.
Pls help me

----------


## frosty16

is the datagridprinter compatable with VS 2005 Express edition?
its just i am tryin to use it in my project adn i have having difficulty as it is saying that datagrid isnt defined and so when i look at the code provided it isnt but if you hover over the text it says it is defined as 'DataGridPrinter.DataGridPrinter' so if i declare this manually it says in the decleratioin that 'DataGridPrinter.DataGridPrinter' isnt defined.
Can someone tell me where i am  going wrong

----------


## Merrion

It was written using VB2005 and it does not use anything that is not present in the express edition.  Make sure you are opening the solution file (*.sln) not one of the projects (*.vbp) as in the latter case the references might not be loaded...

----------


## funch

Hi,

Thank you for the DataGridView Printer, awesome work!!!  

I too had some problems getting it to work, but it was minor stuff so I posted the code below (You still need to add the Class to your project):

Thank you!
Funch

Public Class Form1

    Dim cnStr As String = "Provider=SQLOLEDB;Initial Catalog=Reporting;Data Source=ncso-exch;"
    Dim myDataGridViewPrinter

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'DG.Rows.Clear()
        Dim rs As New ADODB.Recordset
        Dim strSQL As String = "select * from Userdata order by username"
        rs.Open(strSQL, cnStr)

        While Not rs.EOF
            DG.Rows.Add()
            DG.Rows(DG.Rows.Count - 1).Cells(0).Value = rs.Fields.Item("Username").Value.ToString.Replace("NCSO\", "")
            DG.Rows(DG.Rows.Count - 1).Cells(1).Value = rs.Fields.Item("MachineName").Value.ToString
            DG.Rows(DG.Rows.Count - 1).Cells(2).Value = rs.Fields.Item("IPAddress").Value.ToString
            DG.Rows(DG.Rows.Count - 1).Cells(3).Value = rs.Fields.Item("LastRun").Value.ToString
            DG.Rows(DG.Rows.Count - 1).Cells(4).Value = rs.Fields.Item("Version").Value.ToString
            DG.Rows(DG.Rows.Count - 1).Cells(5).Value = rs.Fields.Item("CMVersion").Value.ToString
            DG.Rows(DG.Rows.Count - 1).Cells(6).Value = rs.Fields.Item("DBServer").Value.ToString
            rs.MoveNext()
        End While
        rs.Close()
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        End
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If SetupThePrinting() Then MyPrintDocument.Print()
    End Sub

    Private Function SetupThePrinting() As Boolean
        Dim MyPrintDialog As PrintDialog = New PrintDialog()

        MyPrintDialog.AllowCurrentPage = False
        MyPrintDialog.AllowPrintToFile = False
        MyPrintDialog.AllowSelection = False
        MyPrintDialog.AllowSomePages = True
        MyPrintDialog.PrintToFile = False
        MyPrintDialog.ShowHelp = False
        MyPrintDialog.ShowNetwork = False

        If MyPrintDialog.ShowDialog() <> System.Windows.Forms.DialogResult.OK Then 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 Then
            MyDataGridViewPrinter = New DataGridViewPrinter(DG, MyPrintDocument, True, True, "Customers", New Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, True)
        Else
            myDataGridViewPrinter = New DataGridViewPrinter(DG, MyPrintDocument, False, True, "Customers", New Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, True)
        End If

        Return True
    End Function

    Private Sub MyPrintDocument_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles MyPrintDocument.PrintPage
        Dim more As Boolean

        Try
            more = MyDataGridViewPrinter.DrawDataGridView(e.Graphics)
            If more Then e.HasMorePages = True
        Catch Ex As Exception
            MessageBox.Show(Ex.Message & vbCrLf & Ex.StackTrace, "caption", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub btnPrintPreview_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrintPreview.Click
        If SetupThePrinting() Then
            Dim MyPrintPreviewDialog As PrintPreviewDialog = New PrintPreviewDialog()
            MyPrintPreviewDialog.Document = MyPrintDocument
            MyPrintPreviewDialog.ShowDialog()
        End If
    End Sub
End Class

----------


## kryles

I tried using the files from the original post in order to print the output of my datagrid, but I get:

System.InvalidCastException: Specified cast is not valid

This is the line specified in the DataGrid class

For nextLine = _CurrentPrintGridLine To Min((_CurrentPrintGridLine + RowsPerPage(_PrintFont, e.Graphics)), CType(_DataGrid.DataSource, System.Data.DataTable).DefaultView.Count)

This is the code I am using:



```
Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click

'Button that prints the datagrid
        If GridPrinter Is Nothing Then
            GridPrinter = New DataGridPrinter(Me.dgInventory)
        End If

        Try
            With Me.printDia  'printDia is PrintPreviewDialogue added manually
                .Document = GridPrinter.PrintDocument
                If .ShowDialog = DialogResult.OK Then
                    GridPrinter.Print()
                End If
            End With
        Catch ex As System.InvalidCastException
            MsgBox(Convert.ToString(ex))
        End Try

    End Sub
```



```
 Private Sub frmInvReport_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'Create connection to Database
        Dim connStr As String
        Dim dbObjConn As New OleDb.OleDbConnection
        connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=InventoryManagement.mdb;"
        dbObjConn.ConnectionString = connStr

        'create SQL statement
        Dim selectString As String = "Select * from Products"

        'create DataAdapter
        Dim sqlDA As New OleDb.OleDbDataAdapter(selectString, connStr)

        'Fill dataset
        Try
            dbObjConn.Open()

            Dim ds As New Data.DataSet
            sqlDA.Fill(ds, "Products")
            dgInventory.CaptionText = "Inventory Report"
            dgInventory.DataSource = ds.DefaultViewManager
        Catch ex As OleDb.OleDbException
            MsgBox(Convert.ToString(ex))
        Finally
            dbObjConn.Close()
        End Try
    End Sub
```


So the datagrid is filled in properly, but when I try printing I get the cast error. If you need the whole project or more information please let me know. 
Thanks  :Smilie:

----------


## Merrion

Yup - it is because the data source of your grid is a *DataSet* rather than a *DataTable* --- the code needs to be altered to cater for this possibility...

----------


## kryles

Well, I started using a dataTable but the examples I was lookign at all end up binding using a dataSet in the end. I'll show you the example I was following to do a dataTable instead.



```
 Dim Table1 As DataTable
            Table1 = New DataTable("Products")
            Dim Row1 As DataRow
            Dim description As DataColumn = New DataColumn("description")
            description.DataType = System.Type.GetType("System.String")
            Table1.Columns.Add("description")

            Row1 = Table1.NewRow()
            'declaring a new row
            Row1.Item("description") = "blah blah blah"
            Table1.Rows.Add(Row1)
```

so far so good it seems. Then the example finishes off by doing this



```
           Dim ds As New Data.DataSet
            ds.Tables.Add(Table1)
            dgInventory.SetDataBinding(ds, "Products")
```

which basically brings me to the exact same problem lol. Can someone kinda guide me in the right direction? *blushes*

----------


## kryles

Gah nvm, I just did



```
dgInventory.DataSource = Table1
```

and voila, works. Thanks a lot Merrion  :Smilie:

----------


## goingcrazy

Is it possible to use the zipped code in vb.net 2003 for datagrids?

----------


## jeric_mandrake

How can i set the paper size?
I mean, make the paper half of its height?


Im using the datagridview printer class
thanks.

----------


## Merrion

Yet another version.

New in this release:
(1) Can work with the DataGrid or DataGridView control
(2) Raises an event to allow custom colouring of a data grid cell e.g.:-


```
    Private Sub GridPrinter_QueryCellFormat(ByVal sender As Object, ByVal e As QueryCellFormatEventArgs) Handles GridPrinter.QueryCellFormat

        '\\ Top 2 clubs go up
        If e.RowNumber <= 2 Then
            e.BackgroundColour = Brushes.AliceBlue
        End If

        If e.ColumnNumber = 0 Then
            If e.CellData.ToString = "Grimsby" Then
                e.TextColour = Brushes.RoyalBlue
            End If
        End If

        '\\ Bottom 2 columns relegation
        If e.RowNumber >= 23 Then
            e.BackgroundColour = Brushes.LightGray
        End If
    End Sub
```

(3) Raises an event to allow you to change the actual text in a cell:


```
    Private Sub GridPrinter_QueryCellData(ByVal sender As Object, ByVal e As QueryCellDataEventArgs) Handles GridPrinter.QueryCellData

        If e.ColumnNumber > 0 And e.CellText = "0" Then
            e.CellText = "Zero"
        End If
    End Sub
```

----------


## adam.syd

My mistake, sample can be run from the project file in VS 2005.

Thanks,
Adam.

_Hi Merrion,

Latest version appears to be in VS 2008, any chance of getting it in VS 2005?

Cheers,
Adam._

----------


## Merrion

Oops - because VS2008 is so much nicer a development environment I have been using it for all my code - guess i forgot to roll this one back for "publication"...

----------


## GSIV

Thanks a lot for sharing this great work, Merrion!  :Smilie:  

I d/l'd your latest version and got it to work right off!

----------


## remya1000

i just tried your DataGridPrinter Class to print my dataGrid. 

and printer is not directly connected to my machine. printer is connected to one of the network machine. and i can access that printer from my machine.

but for me while running this program its creating an error. 



> An unhandled exception has occurred in your application. if you click Continue, the application will ignore this error and attempt to continue. If you clicknQuit, the application will be shut down immediately.
> 
> Specified Cast in Not Valid.


if you have any idea what's wrong with this program, please let me know...Please help me....

thanks in advance....

----------


## Merrion

As per the post a few above this, it falls over if the datasource of the datagrid is something other than a Datatable....because it can't get the table column names.

----------


## remya1000

its working perfectly... 

for me problem occurs because i'm not taking the datatable values to datagrid. before i was taking values from dataview to datagrid. when i tried to called datatable values to datagrid... then it works perfectly.... 

thanks a lot for your reply and for this post... its a good example and sure i will rate this post... 

excelent work.... once again thanks a lot for this post....

----------


## tlcred

is there a way to use DataGridViewPrinter or DataGridPrinter class to print more than 1 datagridview controls ? I can have 3-5 on the same winform.

Thnxs in advance

----------


## Merrion

If you don't require the subsequent grid(s) to start on the same page as the fist grid ends on you could just have one DataGridprinter class for each grid on your form and call their Print methods in sequence.  

You would only be able to preview one grid at a time, however.

----------


## shyguyjeff

Merrion your sample is very nice...I like it but do you have any idea if i use listview instead of datagrid? I am using a listview right now on my current program. Could you give me an idea on how to do that? or what if i want to print on my textbox..Thanks in advance Merrion..Have a nice day and God Bless.... :Smilie:

----------


## frankwhite

Hey people was wondering someone could offer me some help please

The program keeps throwing that error, I do have a datatable and im using vb 2003.

Any help or suggestions?  Thanks

----------


## Merrion

You'd need to expand the [Details] button so that we can see what is occuring...

----------


## frankwhite

Hey I found out what the problem was, during the form load event I had my own table styles and I set some of the values to 0 when it should have been 1.

Working now perfectly thanks buddy  :Thumb:

----------


## Drools

I'm missing something, my PrintPreview comes up empty? I'm using a  DataGridView.

My Code Code:
[CODE]
#Region "Private members"
    Private WithEvents GridPrinter As DataGridPrinter
#End Region
 Private Sub PrintPreviewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintPreviewToolStripMenuItem.Click
        GridPrinter = New DataGridPrinter(Me.MfgCostBDDataGridView)
        With Me.PrintPreviewDialog1
            .Document = GridPrinter.PrintDocument
            If .ShowDialog = DialogResult.OK Then
                GridPrinter.Print()
            End If
        End With
    End Sub[/CODE]

thanks

----------


## VB_Beginner

I'm trying to use this class but it doesn't work. When I run my program the user has to click a button to show the data from the database into a datagrid. If the user doen't click that button (there's nothing in the datagrid) then the print button works but there's nothing to print - it's just a blank page. But if there's data in the datagrid then the user clicks print then the debuggin stops at this line:

For nextLine = _CurrentPrintGridLine To Min((_CurrentPrintGridLine + RowsPerPage(_PrintFont, e.Graphics)), CType(_DataGrid.DataSource, System.Data.DataTable).DefaultView.Count)

and it says

InvalidCastException was unhandled by user code

Unable to cast object of type 'System.Data.DataSet' to type 'System.Data.DataTable'

What does that mean or how do i fix that?

----------


## Merrion

It means you need to set the DataGrid's *DataSource* member to a Datatable...
(as per the post Oct 17th, 2007 05:02 PM)

----------


## VBLearner6

> The DataGridPrinter is a class that you can add to your applications to print (or preview) a data grid in a nciely formatted way.
> 
> The class allows you to control settings such as the header height, footer height, header font, grid font, footer font, grid line colour, header border colour, inter section spacing and so on.
> 
> The class takes care of putting the grid headings at the top of each page and generating a new page if the grid rows exceed one page etc.
> 
> Any comments or suggestions?


I am using VB6. When I try to open it I coudn't. How can I use it in my program to get the print from a DataGrid?

Thanks

----------


## VBLearner6

> The DataGridPrinter is a class that you can add to your applications to print (or preview) a data grid in a nciely formatted way.
> 
> The class allows you to control settings such as the header height, footer height, header font, grid font, footer font, grid line colour, header border colour, inter section spacing and so on.
> 
> The class takes care of putting the grid headings at the top of each page and generating a new page if the grid rows exceed one page etc.
> 
> Any comments or suggestions?


Hi, I am using VB6. I have downloaded the zip file *(DataGridPrinter_src)*and unzipped it. But I cannot pen it. How can I use it in my program to get the print from a DataGrid?


Thanks

----------


## VB_Beginner

> It means you need to set the DataGrid's *DataSource* member to a Datatable...
> (as per the post Oct 17th, 2007 05:02 PM)



How do I do that??

----------


## Merrion

Start from Post 31...

----------


## robyn.berry

....

----------


## Merrion

You would need to use Graphics.DrawImage to print the picture in the PrintPage handler.

----------


## lordpuza

excellent work merrion!

thank you thank you!!!

i just moved to vb.net (08)

and dunno what to do to get my printworks done!


i have some questions though ,,

you can set the width of data displayed by adjusting column width (hehehe they asked you many times for this column thing) which is now proportional to your source grid.

how can you increase the size of your cell heigth?

i have data like (lets pretend that is in the cell) :

hello
world <- a part of this is seen

please help me increase the row width ... thank you

i have a feeling that this is possible, i only not know how to...


also,

in the cell gutter, it is 1-10 right? i set it to ten , and it generates an error 
I looked at ur code and the condition is 



```
if Value <0 OrElse Value >=10
```

maybe it needs a tweak? correct me if im wrong



many thanks merrion! your datagrid printer makes printing so easy!

----------


## superdave

Hi Merrion,

 Thanks for your code.   One question:  How do I increase the margin of the output?

Thanks, Dave

----------


## superdave

Well, 

 The solution was easy enough.  Figured I would post for others like me.  Notice the margin assignment below.



```
        With Me.PrintPreviewDialog1
            .Document = GridPrinter.PrintDocument
            .Document.DefaultPageSettings.Margins.Left = 50
            .Document.DefaultPageSettings.Margins.Right = 50
            If .ShowDialog = DialogResult.OK Then
                GridPrinter.Print()
            End If
        End With
```

Dave

----------


## angelica

Hey,

Why is it I get these errors.  Im using visual studio 2005. Is there a way I can solve this printing problem please






```
Warning	2	Function without an 'As' clause; return type of Object assumed.	C:\DataGridPrinter_src\DataGridPrinter\DataGridPrinter.vb	410	21	DataGridPrinter

Warning	3	Unused local variable: 'x'.	C:\DataGridPrinter_src\DataGridPrinter\DataGridPrinter.vb	419	13	DataGridPrinter

Warning	4	Unused local variable: 'y'.	C:\DataGridPrinter_src\DataGridPrinter\DataGridPrinter.vb	419	26	DataGridPrinter

Warning	5	
Function 'DrawCellString' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.	C:\DataGridPrinter_src\DataGridPrinter\DataGridPrinter.vb	441	5	DataGridPrinter
```

----------


## Merrion

> Warning	2	Function without an 'As' clause; return type of Object assumed.	C:\DataGridPrinter_src\DataGridPrinter\DataGridPrinter.vb	410	21	DataGridPrinter


Because I am human and fallible I didn't put any return type on the function declared on line 410.  In fact it should probably be changed to be a sub not a function?




> Warning	3	Unused local variable: 'x'.	C:\DataGridPrinter_src\DataGridPrinter\DataGridPrinter.vb	419	13	DataGridPrinter


Because I am human and fallible I didn't remove the variable declaration 'x' on line 419 when I removed the code that used it.  It can be removed.




> Warning	4	Unused local variable: 'y'.	C:\DataGridPrinter_src\DataGridPrinter\DataGridPrinter.vb	419	26	DataGridPrinter


Because I am human and fallible I didn't remove the variable declaration 'y' on line 419 when I removed the code that used it.  It can be removed.




> Warning	5	
> Function 'DrawCellString' doesn't return a value on all code paths. A null reference exception could


Because I am human and fallible etc.

----------


## VBLearner6

> Thanks a lot for sharing this great work, Merrion!  
> 
> I d/l'd your latest version and got it to work right off!


Hi,

Can I use it with VB6 application so that I can use it in my vb6 project to print the grids?

----------


## angelica

HI Merrion,

Can you please update the whole thing and is it possible for me (not being so much of an expert in vb.net) to print from a dataset and dataview?

Thanks and keep up the good work on this Forum.

cheers

----------


## micki_free

I am having a bit of a strange problem. I am trying to Print out a Datagridview using a PrintPreviewDialog. The Datagridview contains the contents of a table.

If I populate the table manually (row by row) everything is fine. If I populate the table using an access database and an OleDbDataReader then I can only see (and subsequently print out) the first page. 

Someone mentioned in an earlier thread that the problem might be resolved by setting the e.HasMorePages property to true. Could someone tell me how to do this

thanks

----------


## micki_free

This is the code that works



```
 Dim MyTable As New DataTable

        MyTable.Columns.Add(New DataColumn("Team", GetType(String)))
        MyTable.Columns.Add(New DataColumn("Played", GetType(Integer)))
        MyTable.Columns.Add(New DataColumn("Goal Difference", GetType(Integer)))
        MyTable.Columns.Add(New DataColumn("Points", GetType(Integer)))


        MyTable.Rows.Add(New Object() {"Shrewsbury", 4, 3, 9})
        MyTable.Rows.Add(New Object() {"Chester", 4, 5, 8})
  
        DataGridView1.DataSource = MyTable
        If GridPrinter Is Nothing Then
            GridPrinter = New DataGridPrinter(Me.DataGridView1)
        End If

        'setting properties of dgview (after adding gridprinter )
        With GridPrinter
            .HeaderText = CStr("Report Dated - " & Today)
            .HeaderHeightPercent = CInt(5)
            .FooterHeightPercent = CInt(0)
            .InterSectionSpacingPercent = CInt(3)
            .PagesAcross = CInt(2)
        End With

        'printpreview prinout
        With Me.PrintPreviewDialog1
            .Document = GridPrinter.PrintDocument
            If .ShowDialog = DialogResult.OK Then
                GridPrinter.Print()
            End If
        End With
```

This is the code that doesn't work



```
 Dim MyTable As New DataTable

        OleDbCommand1.CommandText = "SELECT Incident_ID, Incident_Date, Incident_Time, Location, Incident_Type, What_Happened, Affected_Individual, Police_Involvement, Crime_Number, Remedial_Action, Assailant FROM AccidentIncident"
        OleDbCommand1.Parameters.AddWithValue("@Incident_ID", "1")
        Dim reader As OleDbDataReader = OleDbCommand1.ExecuteReader()
        MyTable.Load(reader)
        reader.Close()

        DataGridView1.DataSource = MyTable
        If GridPrinter Is Nothing Then
            GridPrinter = New DataGridPrinter(Me.DataGridView1)
        End If

        'setting properties of dgview (after adding gridprinter )
        With GridPrinter
            .HeaderText = CStr("Report Dated - " & Today)
            .HeaderHeightPercent = CInt(5)
            .FooterHeightPercent = CInt(0)
            .InterSectionSpacingPercent = CInt(3)
            .PagesAcross = CInt(2)
        End With

        'printpreview prinout
        With Me.PrintPreviewDialog1
            .Document = GridPrinter.PrintDocument
            If .ShowDialog = DialogResult.OK Then
                GridPrinter.Print()
            End If
        End With
```

----------


## walkesh

I am using Merrion's method for printing the contents of my datagridview.  It works great.  I do have one question though.  With my data grid view, I have set the text that shows up for each row using DataGridView1.Rows(x).HeaderCell.Value.  Is there a way to have these text items also show up in the printing of the datagridview contents?

Thanks!

----------


## Rando

> This is the code that works
> 
> 
> 
> ```
> 
>         If GridPrinter Is Nothing Then
>             GridPrinter = New DataGridPrinter(Me.DataGridView1)
>         End If
> ...


I'm trying to use this code in VB.NET 2008 and it has no clue what 'GridPrinter' is. Am I missing something? was I supposed to import a class or something? Thanks for any help.

Name 'GridPrinter' is not declared.
Type 'DataGridPrinter' is not defined.

----------


## superdave

Look at post #50 in this thread as it defines GridPrinter.

But, if you have DataGridPrinter undefined, then you have not included the reference to your solution.

I would suggest go back and read Merrions post.   There is also more info at the CodeProject on his package.

----------


## Rando

Alright, I took care of those errors but I have a slight issue

The class says it can't convert my DataGridViews to DataGrids...so this class was made for vb 2005. I tried setting it to DataGridView instead of DataGrid but TableStyles no longer exists in the DataGridView

Value of type 'System.Windows.Forms.DataGridView' cannot be converted to 'System.Windows.Forms.DataGrid'.

----------


## superdave

Come on now....

A line like this does define a variable.

Private WithEvents GridPrinter As DataGridPrinter

----------


## Rando

I have a temporary work around... I copied the DataGrid from his VB 2003 document and pasted it into my VB 2008 document. I've hidden it outside of my form and the printer class is feeding from that DataGrid. If anyone knows how to fix it for a DataGridView, that would be great.

----------


## korae

I added this lines in the form load of DataGridPrinter by Merrion


added code Code:
Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Network_Info.mdb"
        Dim myConnection As OleDbConnection = New OleDbConnection
        myConnection.ConnectionString = connString
        ' create a data adapter
        Dim da As OleDbDataAdapter = New OleDbDataAdapter("Select DateRecorded As [Date Recorded], Format([TimeRecorded],'HH:MM:SS AM/PM') As [Time Recorded], Computer_Name As [Computer Name], Fastest_Download_Speed & ' Kb/s' As [Fastest Download Speed] , Fastest_Upload_Speed & ' Kb/s' As [Fastest Upload Speed], Average_Download_Speed & ' Kb/s' As [Average Download Speed], Average_Upload_Speed & ' Kb/s' As [Average Upload Speed], Total_Downloads & ' KB' As [Total Downloads], Total_Uploads & ' KB' As [Total Uploads], IP_Address, ElapsedTime As [Elapsed Time] from Computer_Connection_Info Order by DateRecorded, TimeRecorded", myConnection)
        ' create a new dataset
        Dim ds As DataSet = New DataSet
        ' fill dataset
        da.Fill(ds, "Computer_Connection_Info")
        ' write dataset contents to an xml file by calling WriteXml method
        ' Attach DataSet to DataGrid
        DataGrid1.DataSource = ds.DefaultViewManager

But I always get an error in these lines: 


code Code:
For nextLine = _CurrentPrintGridLine To Min((_CurrentPrintGridLine + RowsPerPage(_PrintFont, e.Graphics)), CType(_DataGrid.DataSource, System.Data.DataTable).DefaultView.Count)
            Call PrintGridLine(e, nextLine)
        Next

It says:

Unable to cast object of type 'System.Data.DataViewManager' to type 'System.Data.DataTable'.

I really don't understand what's going wrong.

----------


## Merrion

The DataGridPrinter only prints dataGrids whos data source is a DataTable.



```
DataGrid1.DataSource = ds.Tables(0)
```

See post 31.

----------


## korae

> Yes - if you change the page layout (in print preview) then the columns and rows get recalculated to fit the page 'automatically'...
> 
> New version (updated with the article) supports background colours for the grid elements.
> 
> Am working on some more defect fixes and enhancements and will post the next release on this thread.


where exactly are you gonna do this? change the page layout to landscape.

----------


## korae

> where exactly are you gonna do this? change the page layout to landscape.


I already figured it out, This is what I did:

With Me.PrintPreviewDialog1
            .Document = GridPrinter.PrintDocument
            .Document.DefaultPageSettings.Landscape = True
            If .ShowDialog = DialogResult.OK Then
                GridPrinter.Print()
            End If
        End With

----------


## Signalman

I wonder if someone could possibly assist, I am very new to VB (2008 Express) and am having some difficulty I am trying to print the contents of a DataGridView1 which has its source defined as Me.DataGridView1.DataSource = config.Tables(0).  With config being a dataset that has been previously filled.

I have imported the DataGridViewPrinter VB code into the project.

With the actual form I have added   Imports appname.DataGridViewPrinter to the top of the form that displays the datagrid.

I have also added the code described in post #20 and have the same errors.  I have corrected  by adding the following to the form that display & Prints the dataview


```
   
      Dim MyPrintDocument As PrintDocument
      Dim MyDataGridViewPrinter As DataGridViewPrinter
```


However, I am still getting 'MyPrintDocument.'  , 'MyDataGridViewPrinter.', MyDataGridView.' & 'MyConstants.' as Name is not declared





> 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 then
> 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)
>         End If


Can someone please assist and explain what I am doing wrong.

----------


## Signalman

I have managed to resolve the issue with MyprintDocument &  MyDataGridViewPrinter not being declared, but within the DIM statement 

```
Dim MyPrintDocument As PrintDocument
```

 Printdocument is Now not defined.

----------


## Merrion

You need to tell the .NET framework where to fiund the *PrintDocument* class.

Try:-




```
Dim MyPrintDocument As System.Drawing.Printing.PrintDocument
```

----------


## MrGTI

Is the source code on The Code Project page really the most up to date version? That was 4 years ago, and i see a lot of revisions in this thread.
.

----------


## Merrion

Possibly not - although it has not changed at all in the last 3 years or so...06-04-2006 is the latest source on my mchine.

----------


## billboy

Where do I find the latest version of this ???

----------


## Simon Canning

I have got the DataGridViewPrinter.zip but am having trouble implementing it. Is there a sample project that uses this class for me too get some ideas off?

thanks

----------


## Simon Canning

OK, I am playing around with the code. I have a couple of errors:

MyDataGridViewPrinter' is not declared and 'MyPrintDocument' is not declared. 

Where do I declare these variables, and what is the syntax?

thanks

----------


## Merrion

Make sure you are opening the solution file (*.sln) not one of the projects (*.vbp) as in the latter case the references might not be loaded...

----------


## johmolan

> OK, I am playing around with the code. I have a couple of errors:
> 
> MyDataGridViewPrinter' is not declared and 'MyPrintDocument' is not declared. 
> 
> Where do I declare these variables, and what is the syntax?
> 
> thanks


Did you figure this out? I have exactly the same problem, I added the .vb file to my project and added the code in the .txt file as well but I got the same errors as you...

----------


## dhilip81

Hello Genius "Merrion" where can i get the latest version ?

Thanks

----------


## sai4455

> Thanks to Berthold Simon, who converted the C# code.


Thank you for posting this code. when I print the grid, the rows are printing with black shaded text and not able to read the data. can you help me?

----------

