2016-12-07 4 views
1

나는 인쇄하고 싶은 DataGridview를 미리 볼 수있는 개발중인 시스템에서 인쇄 미리보기 기능을 만들고 있습니다. ooopsoft의 codes을 참조로 사용했는데 약간의 문제를 제외하고는 문제가 없습니다.vb.net에서 헤더가있는 datagridview 테이블을 인쇄하는 방법은 무엇입니까?

문제 : 당신이 볼 수있는 일련 번호 1과 DGV 행이 누락되는 것을

enter image description here

. 헤더가 첫 번째 행을 덮어 쓴 것으로 보입니다. 나는 그것을 해결하는 방법을 무수히 시도했지만, 나는 여전히 해결책을 찾을 수 없다. 인쇄 미리보기 대화 상자를 종료하고 다시 열어 보았습니다. 그러나 this은 제가 얻은 결과입니다. 나는 코드 줄을 놓치고 있다고 생각하지만, 나는 무엇을 알아낼 수 없다. 도와주세요.

+0

데이터 세트를 사용해 보시기 바랍니다. 출력 만 받고 싶다고 가정합니다. 어쩌면 당신은 보고서 테이블의 행마다 datatable에서 각 데이터를 바인딩 할 수 있습니다. 그것은 플롯 된 데이터 필드마다 헤더를 자동으로 생성합니다. – GNMercado

+0

버그는'For Each cell' 루프에 있습니다. 헤더가'(newpage)'**이거나 ** 첫 번째 행 데이터를 출력한다는 것을 알 수 있습니다. 둘 다해야합니다. 새 페이지의 헤더를 인쇄 한 다음 ** 첫 번째 행을 인쇄하십시오. 새 페이지 코드를 자체 루프에 넣기 만하면됩니다. – Plutonix

+0

@GNMercado Microsoft Report Viewer를 사용하고 싶습니까? 난 이미 그걸 줬어,하지만 예외를 받고 있어요'SQL datetime 값을 system.datetime'으로 변환 할 수 없습니다. – Lucynda

답변

4

original code 좋은 시작이다하지만 버그와 inefficiecies의 몇 가지가 있습니다

  • 그것은 헤더 또는 새 페이지가 첫 번째 행을 인쇄 할 newpage 플래그를 사용합니다. 분명히 두 가지 작업을 원할 것입니다.
  • 열 머리글 인쇄는 데이터 인쇄 루프에 전혀 필요하지 않으므로
  • 기본값이 아닌 보이지 않는 열이나 열은 허용되지 않습니다 정렬, 당신이 계정하려는 다른 설정이있을 수 있습니다.
  • 실제로 올바른 행 번호를 인쇄하지 않기 때문에 이전 페이지의 마지막 행을 새 페이지의 첫 번째 행으로 다시 인쇄한다는 것을 알게되면 수정할 수 있습니다.
  • 내부 제본 또는 텍스트가 격자 선에 너무 가까이 인쇄되지 않도록 여유가있다
  • -이 단지 하나의 오프셋 (offset) 또는 2
  • 또한 불필요하게 singleRectangleF을 사용하고 사용 그것은 또한 준비되지
  • 다시 표시되거나 인쇄 될 문서. 버튼 클릭 또는 BeginPrint 이벤트에서 mRownewpage을 재설정 할 수도 있습니다.

헤더 행의 색을 지정하고 RowPrePaint 규칙을 구현하는 방법을 보여주는 몇 가지 의견을 추가했습니다.

Private mRow As Integer = 0 
Private newpage As Boolean = True 

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

    ' sets it to show '...' for long text 
    Dim fmt As StringFormat = New StringFormat(StringFormatFlags.LineLimit) 
    fmt.LineAlignment = StringAlignment.Center 
    fmt.Trimming = StringTrimming.EllipsisCharacter 
    Dim y As Int32 = e.MarginBounds.Top 
    Dim rc As Rectangle 
    Dim x As Int32 
    Dim h As Int32 = 0 
    Dim row As DataGridViewRow 

    ' print the header text for a new page 
    ' use a grey bg just like the control 
    If newpage Then 
     row = dgvZZ.Rows(mRow) 
     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 dgvZZ.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 
         rc.Offset(2, 0) 
       End Select 

       e.Graphics.DrawString(dgvZZ.Columns(cell.ColumnIndex).HeaderText, 
              dgvZZ.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 dgvZZ.RowCount - 1 
     ' no need to try to print the new row 
     If dgvZZ.Rows(thisNDX).IsNewRow Then Exit For 

     row = dgvZZ.Rows(thisNDX) 
     x = e.MarginBounds.Left 
     h = 0 

     ' reset X for data 
     x = 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 

       e.Graphics.DrawRectangle(Pens.Black, rc) 

       Select Case dgvZZ.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 
         rc.Offset(2, 0) 
       End Select 

       e.Graphics.DrawString(cell.FormattedValue.ToString(), 
             dgvZZ.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.HasMorePages = True 
      ' mRow -= 1 causes last row to rePrint on next page 
      newpage = True 
      Return 
     End If 
    Next 


End Sub 
DGV에 보이지 않는로 설정된 Id 열이 있음을

enter image description hereenter image description here

Color 열은 중앙 및 Price는 왼쪽으로 정렬됩니다 - 이러한 모든 설정이 컨트롤에서 선택됩니다. 또한 텍스트가 눈금 선에서 약간 벗어났습니다. 마지막 글 머리 위

, 는 또한 mRownewpage 중 하나의 버튼 클릭이나 BeginPrint 경우에 재설정 할 것입니다. 당신이 mRow 변수가 모든 행이 인쇄 된 것을 나타냅니다 미리 후

Private Sub PrintDocument1_BeginPrint(sender As Object, 
      e As PrintEventArgs) Handles PrintDocument1.BeginPrint 
    mRow = 0 
    newpage = True 
    PrintPreviewDialog1.PrintPreviewControl.StartPage = 0 
    PrintPreviewDialog1.PrintPreviewControl.Zoom = 1.0 
End Sub 

:이 의미한다.사용자가 인쇄를 클릭하거나 다른 미리보기로 돌아 가면 아무 것도 인쇄되지 않습니다. 또한이 코드는 표시 할 첫 번째 페이지와 초기 확대/축소를 재설정합니다.

+0

코드를 제공해 주셔서 감사합니다. 그것은 코딩 코딩에 대한 새로운 통찰력을 많이주었습니다. 나는 그것을 시험해 보았습니다. 머리글과 첫 번째 행이 미리보기에서 나왔지만 두 번째 행이 없어져서 시퀀스가 ​​'1,3,4'입니다. – Lucynda

+0

업데이트 : 코드 문제와 제가 생각한 몇 가지 문제를 해결했습니다. 질문에 코드를 게시하고 내가 변경 한 내용에 대해 의견을 말합니다. – Lucynda

+0

분명히 눈치 채지 못한 것을 고칠 수있는 수정이있었습니다. 새로운 페이지 테스트는 각 행에 대해 수행 할 필요가 없습니다. 헤더 인쇄는 시작시 한 번만 수행 할 수 있습니다. – Plutonix

관련 문제