Printing from datagridview

I'm sure this has probably been asked before, but I can't find it.
I’m using a DataGridView to display data from a SQL database and I would like to be able to print it. How do I do that My problem is grabbing the data. I simply don’t know how to get the data from the DataGridView. The best thing would be if I could grab and print the entire table but anyway to grab the data and print it in a readable way would be great.

Thanks in advance




Answer this question

Printing from datagridview

  • VBRocksLikeMad

    Hi,

    You can get data from the DataGridView by iterating through the rows in the DataGridView.Rows collection. Code similar to the following should work:

    Dim line As String

    For Each row As DataGridViewRow In CustomersDataGridView.Rows
    line = String.Empty

    For Each cell As DataGridViewCell In row.Cells
    line += cell.Value.ToString() & vbTab
    Next

    ' Render line to printer here

    Next

    This code places data from each row of the grid into a string, with columns separated by a tab character. If you are looking for information on how to render this to the printer, there is a pretty good code sample at http://msdn.microsoft.com/library/default.asp url=/library/en-us/cpref/html/frlrfsystemdrawingprintingprintdocumentclasstopic.asp that shows how to send lines of text to the printer.

    If your goal here is to print something that looks a lot like the DataGridView representation on the screen, you might consider using reports. You can add a new report to your project by right-clicking on the project node in Solution Explorer and selecting Add New Item. Then select Report in the Add New Item dialog. You can then design your report much in the same way you desing Windows Forms. Specifically in this case you could use the Table control (drag from the Toolbox) and then add the columns from your database to it by dragging them from the Data Sources Window onto the control. You can then drag a ReportViewer onto your Windows Form and set it to view your report (on the ReportViewer smart tag). The report viewer gives you previewing, printing, and pagination for free.

    I hope this helps.



  • Drew Marsh

    hi iam using Vb Express

    you mentioned about a report, iam also trying to print a DataGridView

    could u explain more on how to get a "report"

    thanks

    edward


  • Ddscool

    Doesn't anyone know how to do this I would really appreciate any help I coud get.


  • szabti

    That should clear it up, thanks a lot.


  • Printing from datagridview