使用printdocument打印多个页面

时间:2013-06-05 16:28:35

标签: vb.net visual-studio-2010 printdocument

我正在制作程序,其中:在datagridview中选择几行后,它会检查是否选择了1个或更多行。如果是,则在一页上打印两份报告(一份报告=半页)如果更多:每页打印两份报告,打印所需页面。问题是,我的代码打印了相同报告(第一行和第二行)的4531456453页:/

代码的基本示例:

yPos = 0
Do While tmpI < mydatagridview.SelectedRows.Count - 1
For Each selectedrow As DataGridViewRow In mydatagridview.SelectedRows
    Dim data as string = mydatagridview.SelectedRows(selectedrow.index).cells(1).value
    Dim data2 as string = mydatagridview.SelectedRows(selectedrow.index).cells(12).value

    e.graphics.drawstring(data, drawfont, (e.graphics.pagebound.width/2-e.graphics.measurestring(data, drawfont).width/2), 25+yPos)
    e.graphics.drawstring(data2, drawfont, (e.graphics.pagebound.width/2-e.graphics.measurestring(data2, drawfont).width/2), 50+yPos)
    yPos += e.pagebounds.height/2
    tmpI += 1 
    If yPos > e.pagebound.height/2 Then
        h = 0
        e.HasMorePages = true
        Exit Sub
    End If
Next selecedrow
Loop

截至目前,正如我之前所说,它打印了无数量的页面,其中包含来自SelectedRows的索引为0和1的数据和数据。

1 个答案:

答案 0 :(得分:1)

希望这有助于...............

Sub PrintIt(ByVal e As System.Drawing.Printing.PrintPageEventArgs, byval nRow as Integer,ByVal nY As Integer) 

    Dim data as string = mydatagridview.SelectedRows(nRow).cells(1).value
    Dim data2 as string = mydatagridview.SelectedRows(nRow).cells(12).value

    e.graphics.drawstring(data, drawfont, (e.graphics.pagebound.width/2-e.graphics.measurestring(data, drawfont).width/2), 25+nY)
    e.graphics.drawstring(data2, drawfont, (e.graphics.pagebound.width/2-e.graphics.measurestring(data2, drawfont).width/2), 50+nY)

End Sub

你的代码中有一些修改..

yPos = 0

If mydatagridview.SelectedRows.Count = 1

    PrintIt(e,0,yPos)

    yPos += e.pagebounds.height/2

    PrintIt(e,0,yPos)

Elseif mydatagridview.SelectedRows.Count > 1

Dim x,n As Integer

    For x = 0 to mydatagridview.SelectedRows.Count-1
        If n = 2 Then
             e.HasMorePages = true
             n = 0
             yPos = 0
         End If 

         PrintIt(e,x,yPos)
         yPos += e.pagebounds.height/2

         n += 1
    Next

End If