Link to home
Start Free TrialLog in
Avatar of Sean Rhudy
Sean RhudyFlag for United States of America

asked on

PRINTING A DATAGRID

Hello, I have a datagrid called eodgrid on a form called endofday.  I have a program called Visual Documents that usually makes printing much easier, but I am stuck on this one.  The following line is giving me an error " 'Table' is not a member of 'System.Windows.Forms.Datagrid' "
Dim aFilter As String = Me.eodgrid.Table(myTableIndex).DefaultView.RowFilter.Trim

Here is all of the code:

Imports System.Data
Public Class Endofday
    '
    'Declarations to print the Grid
    '
    Private myLastColPrinted As Integer = -1
    Private myPageWidthExceeded As Boolean = False
    Private myPageNo As Integer = 0
    Private myLinesPrintedSoFar As Integer = 0
    Private myRowsProcessedSoFar As Integer = -1
    Private myDataSetRows As Integer = 0
    Private myTableIndex As Integer = 0
    Private myFilteredRows As DataRow()
    Private myDatasetFiltered As Boolean = False
    Private myDrawBrush As New SolidBrush(Color.Black)              'Create the default brush
    Private myDrawFont As New Font("Courier New", 8)                'Modify this line to change the font
    Dim con As New OleDb.OleDbConnection
    Dim sql As String
    Dim ds As New DataSet
    Private Cmd As New OleDb.OleDbCommand
    Dim da As OleDb.OleDbDataAdapter
    Private Sub Endofday_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'ReceiptDataSet5.totalquery' table. You can move, or remove it, as needed.
        Me.TotalqueryTableAdapter.Fill(Me.ReceiptDataSet5.totalquery)
        'TODO: This line of code loads data into the 'ReceiptDataSet4.pdatequery' table. You can move, or remove it, as needed.
        Me.PdatequeryTableAdapter.Fill(Me.ReceiptDataSet4.pdatequery)
        Me.TotalqueryTableAdapter.Fill(Me.ReceiptDataSet5.totalquery)
        con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:/backup/receiptprogram/receiptmanagement/receipt.mdb"
        con.Open()
        Dsendofday.Clear()
        'Cmd.CommandText = "SELECT ReceiptNo, PolicyNo, pmt1, pmt2, pmt3, type1, type2, type3, total, rcvdby, firstname, lastname, typeaccount, company, checkmaker, checkno, Datercvd, notebox FROM Receiptinfo WHERE pdate = null"
        'Cmd.CommandType = CommandType.Text
        'da = New OleDb.OleDbDataAdapter(Cmd)
        'da.Fill(Dsendofday.Receiptinfo)
        con.Close()
    End Sub

    Private Sub btnBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBack.Click
        Me.Visible = False
        frontpage.Visible = True
    End Sub

    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Try
            AddHandler PrintDocument1.PrintPage, AddressOf Me.PrintDocument1_PrintPage
            PrintDocument1.Print()
        Catch ex As Exception
            MessageBox.Show("An error occurred while printing", ex.ToString())
        End Try
    End Sub
    Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim myNumberOfColumns As Integer
        Dim aTblIndex As Integer = 0
        Dim myDataSetToPrint As DataSet = Me.ReceiptDataSet4                             'Set here the DataSet to print
        Dim GridLeft As Single = 0.2395833                                              'The left position of the Grid
        Dim GridRight As Single = 8                                             'The Right position of the Grid
        Dim Gridtop As Single = 1.3125                                               'The top position of the Grid
        Dim GridBottom As Single = 7.885417                                           'The bottom position of the Grid
        Dim aScaleFactor As Single = 14.45
        Dim aLeftMargin As Integer = Int((GridLeft * 1440) / aScaleFactor)
        Dim aRightMargin As Integer = Int((GridRight * 1440) / aScaleFactor)
        Dim aTopMargin As Integer = Int((Gridtop * 1440) / aScaleFactor)
        Dim aBottomMargin As Integer = Int((GridBottom * 1440) / aScaleFactor)
        Dim myLineThreshold As Integer = 500
        Dim aFilter As String = Me.eodgrid.Table(myTableIndex).DefaultView.RowFilter.Trim
        Dim aValue As String
        Dim aTextHeight As Single = myDrawFont.GetHeight(e.Graphics)
        Dim aXPos As Single = aLeftMargin
        Dim aYPos As Single = aTopMargin
        Dim aColIndex As Integer = 0
        Dim aRowIndex As Integer
        Dim aLinesFilled As Integer
        Dim aLinesPerPage As Integer = 0
        Dim aCharactersFitted As Integer
        Dim aLinesPrintedThisPage As Integer = 0
        Dim aColsToPrint As Integer
        Dim aLinesPrintedSoFar As Integer = myLinesPrintedSoFar
        Dim aFirstColToPrint As Integer
        Dim aRow As DataRow
        Dim aCol As DataColumn
        Dim aStringSize As New SizeF
        Dim aLayoutSize As New SizeF
        Dim aNewStringFormat As New StringFormat
        Dim aPrintIt As Boolean
        Dim GridLinesColor As Pen = New Pen(Color.FromArgb(255, 128, 128, 128)) 'Draw gridlines in Gray
        Dim DrawGridLines As Boolean = True                                     'Set True or False to show or hide the gridlines
        Dim myfont As Font
        Dim myBrush As SolidBrush
        Dim MyPen As Pen
        Dim X1 As Single, X2 As Single, Y1 As Single, Y2 As Single

        myNumberOfColumns = myDataSetToPrint.Tables(aTblIndex).Columns.Count - 1
        myPageNo = 0
        myLinesPrintedSoFar = 0
        If aFilter = "" Then
            myDatasetFiltered = False
            myDataSetRows = myDataSetToPrint.Tables(myTableIndex).Rows.Count - 1
        Else
            myDatasetFiltered = True
            myDataSetRows = myDataSetToPrint.Tables(myTableIndex).DefaultView.Count - 1
            myFilteredRows = myDataSetToPrint.Tables(myTableIndex).Select(aFilter)
        End If

        e.Graphics.PageUnit = GraphicsUnit.Display

        With myDataSetToPrint.Tables(myTableIndex).Columns
            If myNumberOfColumns = 0 Then
                aColsToPrint = .Count
            Else
                If myNumberOfColumns > .Count Then
                    aColsToPrint = .Count
                Else
                    aColsToPrint = myNumberOfColumns
                End If
            End If
        End With

        aLayoutSize.Height = aTextHeight
        aLinesPerPage = Int((aBottomMargin - aTopMargin) / aTextHeight)
        aNewStringFormat.FormatFlags = StringFormatFlags.NoWrap
        myPageNo += 1

        'Print the rest of the objects
        e.Graphics.PageUnit = GraphicsUnit.Inch




        '
        'Print Captions
        '
        myBrush = New SolidBrush(Color.FromArgb(255, 18, 0, 0))
        myfont = New Font("MS Sans Serif", 14, FontStyle.Regular)
        e.Graphics.DrawString("END OF DAY", myfont, myBrush, 3.84375, 0.2604167)




        'Print the dataset
        e.Graphics.PageUnit = GraphicsUnit.Display
        aLayoutSize.Width = aRightMargin - aLeftMargin

        myPageWidthExceeded = False
        aFirstColToPrint = myLastColPrinted + 1

        For aColIndex = aFirstColToPrint To aColsToPrint
            aCol = myDataSetToPrint.Tables(myTableIndex).Columns(aColIndex)

            aPrintIt = True
            aStringSize = e.Graphics.MeasureString(aCol.Caption, myDrawFont)
            aLayoutSize.Width = (aRightMargin - aLeftMargin) / (aColsToPrint + 1)

            aStringSize = e.Graphics.MeasureString(aCol.Caption, myDrawFont, _
                          aLayoutSize, aNewStringFormat, aCharactersFitted, aLinesFilled)
            If aPrintIt Then
                If (aXPos + aLayoutSize.Width) <= aRightMargin Then
                    e.Graphics.DrawString(Mid(aCol.Caption, 1, aCharactersFitted), myDrawFont, myDrawBrush, aXPos, aYPos)
                    aXPos += aLayoutSize.Width
                    myLastColPrinted = aColIndex
                Else
                    myPageWidthExceeded = True
                    Exit For
                End If
            Else
                myLastColPrinted = aColIndex
            End If
        Next

        aLinesPrintedThisPage += 1

        For aRowIndex = myLinesPrintedSoFar To myDataSetRows
            If myDatasetFiltered Then
                aRow = myFilteredRows(aRowIndex)
            Else
                aRow = myDataSetToPrint.Tables(myTableIndex).Rows.Item(aRowIndex)
            End If

            myRowsProcessedSoFar += 1

            If aRow.RowState <> DataRowState.Deleted Then

                If DrawGridLines Then e.Graphics.DrawLine(GridLinesColor, aLeftMargin, aYPos, aRightMargin, aYPos)
                aXPos = aLeftMargin
                aYPos += aTextHeight

                For aColIndex = aFirstColToPrint To myLastColPrinted
                    aValue = aRow(aColIndex).ToString
                    aCol = myDataSetToPrint.Tables(myTableIndex).Columns(aColIndex)
                    aStringSize = e.Graphics.MeasureString(aValue, myDrawFont, aLayoutSize, aNewStringFormat, aCharactersFitted, aLinesFilled)

                    If aPrintIt Then
                        If aValue.Length > aCharactersFitted Then
                            aValue = Mid(aValue, 1, aCharactersFitted)
                        End If
                        If DrawGridLines Then e.Graphics.DrawLine(GridLinesColor, aXPos, aYPos - aTextHeight, aXPos, aYPos + aTextHeight)
                        e.Graphics.DrawString(aValue, myDrawFont, myDrawBrush, aXPos, aYPos)
                        aXPos += aLayoutSize.Width
                        aLayoutSize.Height = aYPos + aTextHeight
                    End If
                Next
                If DrawGridLines Then
                    e.Graphics.DrawLine(GridLinesColor, aXPos, aYPos - aTextHeight, aXPos, aYPos + aTextHeight)
                    e.Graphics.DrawLine(GridLinesColor, aLeftMargin, aYPos, aRightMargin, aYPos)
                    e.Graphics.DrawLine(GridLinesColor, aLeftMargin, aYPos + aTextHeight, aRightMargin, aYPos + aTextHeight)
                End If
                aLinesPrintedThisPage += 1
                myLinesPrintedSoFar += 1
                If aLinesPrintedThisPage > aLinesPerPage Then Exit For
                If myLinesPrintedSoFar > myDataSetRows Then Exit For
            End If

            If myRowsProcessedSoFar > myDataSetRows Then Exit For
        Next

        If myPageWidthExceeded Then
            myLinesPrintedSoFar = aLinesPrintedSoFar
        End If

        If myLastColPrinted >= aColsToPrint Then
            myLastColPrinted = -1
        End If

        If myLinesPrintedSoFar <= myDataSetRows And myRowsProcessedSoFar < myDataSetRows Then
            e.HasMorePages = True
        Else
            e.HasMorePages = False
            myPageNo = 0
            myLinesPrintedSoFar = 0
            myRowsProcessedSoFar = -1
            myLastColPrinted = -1
        End If

        aCol = Nothing
        aRow = Nothing
        Exit Sub

ErrorHandler:
        Throw New Exception("Error formatting report output.", Err.GetException)

    End Sub


End Class
Avatar of Jeff Certain
Jeff Certain
Flag of United States of America image

If I'm not mistaken, you have to get to the table through the datasource?
Avatar of Sean Rhudy

ASKER

please elaborate.
Ok, I've gone back to the basics, How can I make this code print in landscape?

Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        PrintDocument1.Print()
    End Sub
    Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim myPaintArgs As New PaintEventArgs(e.Graphics, New Rectangle(New _
              Point(0, 0), Me.Size))
        Me.InvokePaint(eodgrid, myPaintArgs)
    End Sub
is this just printing a graphic of it?
Please close question, I used the following code:

Private Sub PrintDocument1_BeginPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles PrintDocument1.BeginPrint

        oStringFormat = New StringFormat
        oStringFormat.Alignment = StringAlignment.Near
        oStringFormat.LineAlignment = StringAlignment.Center
        oStringFormat.Trimming = StringTrimming.EllipsisCharacter

        oStringFormatComboBox = New StringFormat
        oStringFormatComboBox.LineAlignment = StringAlignment.Center
        oStringFormatComboBox.FormatFlags = StringFormatFlags.NoWrap
        oStringFormatComboBox.Trimming = StringTrimming.EllipsisCharacter

        oButton = New Button
        oCheckbox = New CheckBox
        oComboBox = New ComboBox



        nTotalWidth = 0
        For Each oColumn As DataGridViewColumn In DataGridView1.Columns

            nTotalWidth += oColumn.Width

        Next
        nPageNo = 1
        NewPage = True
        nRowPos = 0

    End Sub

    Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage

        Static oColumnLefts As New ArrayList
        Static oColumnWidths As New ArrayList
        Static oColumnTypes As New ArrayList
        Static nHeight As Int16

        Dim nWidth, i, nRowsPerPage As Int16
        Dim nTop As Int16 = e.MarginBounds.Top
        Dim nLeft As Int16 = e.MarginBounds.Left

       
        e.PageSettings.Landscape = True

        If nPageNo = 1 Then

            For Each oColumn As DataGridViewColumn In DataGridView1.Columns

                nWidth = CType(Math.Floor(oColumn.Width / nTotalWidth * nTotalWidth * (e.MarginBounds.Width / nTotalWidth)), Int16)

                nHeight = e.Graphics.MeasureString(oColumn.HeaderText, oColumn.InheritedStyle.Font, nWidth).Height + 11

                oColumnLefts.Add(nLeft)
                oColumnWidths.Add(nWidth)
                oColumnTypes.add(oColumn.GetType)
                nLeft += nWidth

            Next

        End If

        Do While nRowPos < DataGridView1.Rows.Count - 1

            Dim oRow As DataGridViewRow = DataGridView1.Rows(nRowPos)

            If nTop + nHeight >= e.MarginBounds.Height + e.MarginBounds.Top Then

                DrawFooter(e, nRowsPerPage)

                NewPage = True
                nPageNo += 1
                e.HasMorePages = True
                Exit Sub

            Else

                If NewPage Then

                    ' Draw Header
                    e.Graphics.DrawString(Header, New Font(DataGridView1.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top - e.Graphics.MeasureString(Header, New Font(DataGridView1.Font, FontStyle.Bold), e.MarginBounds.Width).Height - 13)

                    ' Draw Columns
                    nTop = e.MarginBounds.Top
                    i = 0
                    For Each oColumn As DataGridViewColumn In DataGridView1.Columns

                        e.Graphics.FillRectangle(New SolidBrush(Drawing.Color.LightGray), New Rectangle(oColumnLefts(i), nTop, oColumnWidths(i), nHeight))
                        e.Graphics.DrawRectangle(Pens.Black, New Rectangle(oColumnLefts(i), nTop, oColumnWidths(i), nHeight))
                        e.Graphics.DrawString(oColumn.HeaderText, oColumn.InheritedStyle.Font, New SolidBrush(oColumn.InheritedStyle.ForeColor), New RectangleF(oColumnLefts(i), nTop, oColumnWidths(i), nHeight), oStringFormat)
                        i += 1

                    Next
                    NewPage = False

                End If

                nTop += nHeight
                i = 0
                For Each oCell As DataGridViewCell In oRow.Cells

                    If oColumnTypes(i) Is GetType(DataGridViewTextBoxColumn) OrElse oColumnTypes(i) Is GetType(DataGridViewLinkColumn) Then

                        e.Graphics.DrawString(oCell.Value.ToString, oCell.InheritedStyle.Font, New SolidBrush(oCell.InheritedStyle.ForeColor), New RectangleF(oColumnLefts(i), nTop, oColumnWidths(i), nHeight), oStringFormat)

                    ElseIf oColumnTypes(i) Is GetType(DataGridViewButtonColumn) Then

                        oButton.Text = oCell.Value.ToString
                        oButton.Size = New Size(oColumnWidths(i), nHeight)
                        Dim oBitmap As New Bitmap(oButton.Width, oButton.Height)
                        oButton.DrawToBitmap(oBitmap, New Rectangle(0, 0, oBitmap.Width, oBitmap.Height))
                        e.Graphics.DrawImage(oBitmap, New Point(oColumnLefts(i), nTop))

                    ElseIf oColumnTypes(i) Is GetType(DataGridViewCheckBoxColumn) Then

                        oCheckbox.Size = New Size(14, 14)
                        oCheckbox.Checked = CType(oCell.Value, Boolean)
                        Dim oBitmap As New Bitmap(oColumnWidths(i), nHeight)
                        Dim oTempGraphics As Graphics = Graphics.FromImage(oBitmap)
                        oTempGraphics.FillRectangle(Brushes.White, New Rectangle(0, 0, oBitmap.Width, oBitmap.Height))
                        oCheckbox.DrawToBitmap(oBitmap, New Rectangle(CType((oBitmap.Width - oCheckbox.Width) / 2, Int32), CType((oBitmap.Height - oCheckbox.Height) / 2, Int32), oCheckbox.Width, oCheckbox.Height))
                        e.Graphics.DrawImage(oBitmap, New Point(oColumnLefts(i), nTop))

                    ElseIf oColumnTypes(i) Is GetType(DataGridViewComboBoxColumn) Then

                        oComboBox.Size = New Size(oColumnWidths(i), nHeight)
                        Dim oBitmap As New Bitmap(oComboBox.Width, oComboBox.Height)
                        oComboBox.DrawToBitmap(oBitmap, New Rectangle(0, 0, oBitmap.Width, oBitmap.Height))
                        e.Graphics.DrawImage(oBitmap, New Point(oColumnLefts(i), nTop))
                        e.Graphics.DrawString(oCell.Value.ToString, oCell.InheritedStyle.Font, New SolidBrush(oCell.InheritedStyle.ForeColor), New RectangleF(oColumnLefts(i) + 1, nTop, oColumnWidths(i) - 16, nHeight), oStringFormatComboBox)

                    ElseIf oColumnTypes(i) Is GetType(DataGridViewImageColumn) Then

                        Dim oCellSize As Rectangle = New Rectangle(oColumnLefts(i), nTop, oColumnWidths(i), nHeight)
                        Dim oImageSize As Size = CType(oCell.Value, Image).Size
                        e.Graphics.DrawImage(oCell.Value, New Rectangle(oColumnLefts(i) + CType(((oCellSize.Width - oImageSize.Width) / 2), Int32), nTop + CType(((oCellSize.Height - oImageSize.Height) / 2), Int32), CType(oCell.Value, Image).Width, CType(oCell.Value, Image).Height))

                    End If

                    e.Graphics.DrawRectangle(Pens.Black, New Rectangle(oColumnLefts(i), nTop, oColumnWidths(i), nHeight))

                    i += 1

                Next

            End If

            nRowPos += 1
            nRowsPerPage += 1

        Loop

        DrawFooter(e, nRowsPerPage)

        e.HasMorePages = False

    End Sub

    Private Sub DrawFooter(ByVal e As System.Drawing.Printing.PrintPageEventArgs, ByVal RowsPerPage As Int32)

        Dim sPageNo As String

        If blnGotNumPages = False Then

            blnGotNumPages = True

            strNumOfPages = Math.Ceiling(DataGridView1.Rows.Count / RowsPerPage).ToString

            sPageNo = nPageNo.ToString + " of " + Math.Ceiling(DataGridView1.Rows.Count / RowsPerPage).ToString

        Else

            sPageNo = nPageNo.ToString + " of " + strNumOfPages

        End If


        ' Right Align - User Name
        e.Graphics.DrawString(sUserName, DataGridView1.Font, Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - e.Graphics.MeasureString(sPageNo, DataGridView1.Font, e.MarginBounds.Width).Width), e.MarginBounds.Top + e.MarginBounds.Height + 7)

        ' Left Align - Date/Time
        e.Graphics.DrawString(Now.ToLongDateString + " " + Now.ToShortTimeString, DataGridView1.Font, Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top + e.MarginBounds.Height + 7)

        ' Center  - Page No. Info
        e.Graphics.DrawString(sPageNo, DataGridView1.Font, Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - e.Graphics.MeasureString(sPageNo, DataGridView1.Font, e.MarginBounds.Width).Width) / 2, e.MarginBounds.Top + e.MarginBounds.Height + 31)

    End Sub
ASKER CERTIFIED SOLUTION
Avatar of PashaMod
PashaMod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial