0% found this document useful (0 votes)
121 views

How To DataGridView Printing in

The document describes how to print the contents of a DataGridView control in VB.Net. It involves adding a PrintDocument control to the form and handling the PrintPage event to draw the DataGridView to a bitmap. The code sample draws the header, cells and formatting of the DataGridView to the printed page.

Uploaded by

pepecr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
121 views

How To DataGridView Printing in

The document describes how to print the contents of a DataGridView control in VB.Net. It involves adding a PrintDocument control to the form and handling the PrintPage event to draw the DataGridView to a bitmap. The code sample draws the header, cells and formatting of the DataGridView to the printed page.

Uploaded by

pepecr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

18/4/22, 14:32 How to DataGridView Printing in VB.

net

Este sitio utiliza cookies de Google para prestar sus servicios y para analizar su tráfico. Tu
dirección IP y user-agent se comparten con Google, junto con las métricas de rendimiento y de
seguridad, para garantizar la calidad del servicio, generar estadísticas de uso y detectar y
solucionar abusos.
MÁS INFORMACIÓN ACEPTAR

How to DataGridView Printing in VB.net 


 Source Code Ph  Tuesday, February 01, 2022  C-sharp  0
Comments

     

Tags

Responsive Advertisement  C-Sha

 C#

 C++

   Datab

 Html

 Java

 JAVA

 MySq

 PHP

 Pytho

 SQL

 Tutor

 Vb.Ne

 Visua

 Visua

Here in the  PrintPage  event we create a Bitmap Object and draw the Blog A

DataGridView to the Bitmap Object. In order to run this vb.net project you  Mar 2
have to drag two buttons ,one for load data and one for print command, and
 Feb 2
drag a PrintDocument control on your form .
 Jan 2

 Dec 2

Home Features  Video Tutorials Downloads Contact us
 Nov 2

https://www.sourcecodeph.com/2022/02/how-to-datagridview-printing-in-vbnet.html 1/7
18/4/22, 14:32 How to DataGridView Printing in VB.net

The DataGridView control provides a customizable table for displaying data.


Este sitio utiliza cookies de Google para prestar sus servicios y para analizar su tráfico. Tu
It gives you number of properties, methods and events to customize its
dirección IP y user-agent se comparten con Google, junto con las métricas de rendimiento y de Seguid
appearance
seguridad, paraand behavior.
garantizar Unfortunately
la calidad thegenerar
del servicio, DataGridView doesn't
estadísticas de usohave a
y detectar y
built in printing
solucionar abusos.functionality . So here we do a tricky way to print the content
of DataGridView . Here we add
MÁSa INFORMACIÓN
PrintDocumentACEPTAR
object to the project and Seg
handle the PrintPage event which is called every time a new page is to be
printed. Here in the PrintPage event we create a Bitmap Object and draw the
DataGridView to the Bitmap Object. Popul

In order to run this vb.net project you have to drag two buttons ,one for load
data and one for print command, and drag a PrintDocument control on your
form . The following picture shows how to drag PrintDocument Object to your
project.

Here is the code

  Dim WithEvents PrintDoc As PrintDocument


    Dim PrintPreviewDialog As PrintPreviewDialog

    Private mRow As Integer = 0


    Private newpage As Boolean = True
    Sub print() Subsc
        PrintDoc = New PrintDocument
        PrintPreviewDialog = New PrintPreviewDialog
        PrintDoc.DefaultPageSettings.PaperSize = New
System.Drawing.Printing.PaperSize("PaperA4", 840, 1000)
        PrintPreviewDialog.Document = PrintDoc
        PrintDoc.DefaultPageSettings.Landscape = True
        PrintPreviewDialog.ShowDialog()
    End Sub



Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e
As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDoc.PrintPage
        Dim YAxis As Integer = 0

        ' sets it to show '...' for long text


        Dim fmt As StringFormat = New
StringFormat(StringFormatFlags.LineLimit)
        fmt.LineAlignment = StringAlignment.Center
        fmt.Trimming
Home Features  = StringTrimming.EllipsisCharacter
Video Tutorials Downloads Contact us 

        Dim y As Int32 = 100 'Dim y As Int32 = e.MarginBounds.Top


https://www.sourcecodeph.com/2022/02/how-to-datagridview-printing-in-vbnet.html 2/7
18/4/22, 14:32 How to DataGridView Printing in VB.net

        Dim rc As Rectangle
Este
      sitio
  Dim utiliza
x Ascookies
Int32 =de
50Google
' Dim para
x Asprestar
Int32 sus servicios y para analizar su tráfico. Tu
dirección IP y user-agent se comparten con Google, junto con las métricas de rendimiento y de
        Dim h As Int32 = 0
seguridad, para garantizar la calidad del servicio, generar estadísticas de uso y detectar y
        Dimabusos.
solucionar row As DataGridViewRow
        e.Graphics.DrawString("SUMMARY ATTENDANCE", New Font("Century
MÁS INFORMACIÓN ACEPTAR
Gothic", 12, FontStyle.Bold), Brushes.Black, New Point(310, YAxis + 15))
        ' e.Graphics.DrawString("Client Name: " & FULLNAME.Text, New
Font("Century Gothic", 10, FontStyle.Bold), Brushes.Black, New Point(100,
YAxis + 50))
        'e.Graphics.DrawString("Date Print: " & Date.Now.ToLongDateString,
New Font("Century Gothic", 10, FontStyle.Bold), Brushes.Black, New
Point(100, YAxis + 75))
        'e.Graphics.DrawString("Total Amount: " & LabelTotalPayment.Text,
New Font("Century Gothic", 10, FontStyle.Bold), Brushes.Black, New
Point(100, YAxis + 100))

        ' print the header text for a new page


        '   use a grey bg just like the control
        If newpage Then
            row = DataGridView1.Rows(mRow)
            x = 50 'x = e.MarginBounds.Left
            For Each cell As DataGridViewCell In row.Cells
                ' since we are printing the control's view,
                ' skip invidible columns
                If cell.Visible Then
                    rc = New Rectangle(x, y, cell.Size.Width, cell.Size.Height)

                    e.Graphics.FillRectangle(Brushes.LightGray, rc)
                    e.Graphics.DrawRectangle(Pens.Black, rc)

                    ' reused in the data pront - should be a function


                    Select Case
DataGridView1.Columns(cell.ColumnIndex).DefaultCellStyle.Alignment
                        Case DataGridViewContentAlignment.BottomRight,
                             DataGridViewContentAlignment.MiddleRight
                            fmt.Alignment = StringAlignment.Far
                            rc.Offset(-1, 0)
                        Case DataGridViewContentAlignment.BottomCenter,
                            DataGridViewContentAlignment.MiddleCenter
                            fmt.Alignment = StringAlignment.Center
                        Case Else
                            fmt.Alignment = StringAlignment.Near

Home Features  Video Tutorials Downloads Contact us
                            rc.Offset(2, 0)

https://www.sourcecodeph.com/2022/02/how-to-datagridview-printing-in-vbnet.html 3/7
18/4/22, 14:32 How to DataGridView Printing in VB.net

                    End Select
Este sitio utiliza cookies de Google para prestar sus servicios y para analizar su tráfico. Tu
dirección IP y user-agent se comparten con Google, junto con las métricas de rendimiento y de
          
seguridad, para garantizar la calidad del servicio, generar estadísticas de uso y detectar y
e.Graphics.DrawString(DataGridView1.Columns(cell.ColumnIndex).HeaderTe
solucionar abusos.
xt,
MÁS INFORMACIÓN ACEPTAR
                                                DataGridView1.Font, Brushes.Black, rc,
fmt)
                    x += rc.Width
                    h = Math.Max(h, rc.Height)
                End If
            Next
            y += h

        End If
        newpage = False

        ' now print the data for each row


        Dim thisNDX As Int32
        For thisNDX = mRow To DataGridView1.RowCount - 1
            ' no need to try to print the new row
            If DataGridView1.Rows(thisNDX).IsNewRow Then Exit For

            row = DataGridView1.Rows(thisNDX)
            x = 50 'x = e.MarginBounds.Left
      h=0

            ' reset X for data


            x = 50 'e.MarginBounds.Left

            ' print the data


            For Each cell As DataGridViewCell In row.Cells
                If cell.Visible Then
                    rc = New Rectangle(x, y, cell.Size.Width, cell.Size.Height)

                    ' SAMPLE CODE: How To 


                    ' up a RowPrePaint rule
                    'If Convert.ToDecimal(row.Cells(5).Value) < 9.99 Then
                    '    Using br As New SolidBrush(Color.MistyRose)
                    '        e.Graphics.FillRectangle(br, rc)
                    '    End Using
                    'End If


Home Features  Video Tutorials Downloads Contact us
                    e.Graphics.DrawRectangle(Pens.Black, rc)

https://www.sourcecodeph.com/2022/02/how-to-datagridview-printing-in-vbnet.html 4/7
18/4/22, 14:32 How to DataGridView Printing in VB.net

Este
      sitio
       utiliza cookies
      Select de Google para prestar sus servicios y para analizar su tráfico. Tu
Case
dirección IP y user-agent se comparten con Google, junto con las métricas de rendimiento y de
DataGridView1.Columns(cell.ColumnIndex).DefaultCellStyle.Alignment
seguridad, para garantizar la calidad del servicio, generar estadísticas de uso y detectar y
              abusos.
solucionar           Case DataGridViewContentAlignment.BottomRight,
                             DataGridViewContentAlignment.MiddleRight
MÁS INFORMACIÓN ACEPTAR
                            fmt.Alignment = StringAlignment.Far
                            rc.Offset(-1, 0)
                        Case DataGridViewContentAlignment.BottomCenter,
                            DataGridViewContentAlignment.MiddleCenter
                            fmt.Alignment = StringAlignment.Center
                        Case Else
                            fmt.Alignment = StringAlignment.Near
                            rc.Offset(2, 0)
                    End Select

                    e.Graphics.DrawString(cell.FormattedValue.ToString(),
                                          DataGridView1.Font, Brushes.Black, rc, fmt)

                    x += rc.Width
                    h = Math.Max(h, rc.Height)
                End If

            Next
            y += h
            ' next row to print
            mRow = thisNDX + 1

            If y + h > e.MarginBounds.Bottom Then 'e.MarginBounds.Bottom


                e.HasMorePages = True
                '  mRow -= 1   \causes last row To rePrint On Next page
                newpage = True
                Return
            End If

        Next

    End Sub


    Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles
btnPrint.Click
        Call print()

Home Features  Video Tutorials Downloads Contact us
    End Sub

https://www.sourcecodeph.com/2022/02/how-to-datagridview-printing-in-vbnet.html 5/7
18/4/22, 14:32 How to DataGridView Printing in VB.net

Este sitio utiliza


    Private Sub cookies de Google para prestarAs
PrintDoc_BeginPrint(sender sus servicios
Object, y para
e As analizar su tráfico. Tu
PrintEventArgs)
dirección IP y user-agent se comparten con Google, junto con las métricas de rendimiento y de
Handles PrintDoc.BeginPrint
seguridad, para garantizar la calidad del servicio, generar estadísticas de uso y detectar y
        mRow
solucionar =0
abusos.
        newpage = True
MÁS INFORMACIÓN ACEPTAR
        PrintPreviewDialog.PrintPreviewControl.StartPage = 0
        PrintPreviewDialog.PrintPreviewControl.Zoom = 1.0
    End Sub

Facebook

Responsive Advertisement

Tags C-sharp c# vb.net Visual Basic .NET visual basic net

     

Posted by:
Source Code Ph

Related Posts

How to DataGridView How to Scan a Barcode Police Crime Record


Printing in VB.net Image in Java Management System in PHP
 February 01, 2022  December 08, 2021 and MySqli
 December 03, 2021

 Previous Post Next Post 

0
Comments
Home Features  Video Tutorials Downloads Contact us 

https://www.sourcecodeph.com/2022/02/how-to-datagridview-printing-in-vbnet.html 6/7
18/4/22, 14:32 How to DataGridView Printing in VB.net

Este sitio utiliza cookies de Google para prestar sus servicios y para analizar su tráfico. Tu
dirección IP y user-agent
Enter se comparten con Google, junto con las métricas de rendimiento y de
your comment...
seguridad, para garantizar la calidad del servicio, generar estadísticas de uso y detectar y
solucionar abusos.
MÁS INFORMACIÓN ACEPTAR

Tags Categori

Against All “Odds” C-plus C-sharp c#


 C#

C++ Database html Java  C++


This channel will help you to learn on how to make a
simple program using these languages: PHP, JAVA TUTORIAL Mysql Database MySqli  Html
MySqli, Microsoft.Net, Visual Basic, Bootstrap, C++,
MySqli Database PHP Python QRCode  Java
JAVA etc, specially for those IT Students and for all
that is willing to learn basic programming. The SQL Tutorial vb.net Visual Basic .NET  MySqli
videos are delivered in a casual and easy-to-
visual basic net  PHP
understand, every tutorial has an explanation in the
description of the video. The tutorials cover a range  Python
of different programming topics including
 SQL
developing for Arduino, NODEMCU and Design,
Finger Print using Arduino, RFID, and many more.  Visual Ba

Email: [email protected]

Design by Theme | Distributed by Gooyaabi Template

https://www.sourcecodeph.com/2022/02/how-to-datagridview-printing-in-vbnet.html 7/7

You might also like