Results 1 to 37 of 37

Thread: [RESOLVED] How to select the page number to print in print preview dialog box?

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Mar 2019
    Posts
    85

    Resolved [RESOLVED] How to select the page number to print in print preview dialog box?

    Hi members
    How i can to select the page number to print in print preview dialog box?

    when i put the page number and try it not effect the print button
    like when i choose to print page 4 and click ok it will print all page
    this is my try
    Code:
     Private Sub PDB_Click1(ByVal sender As Object, ByVal e As EventArgs) Handles PDB.Click
                 PrintDialog1.AllowSelection = True
                 PrintDialog1.AllowCurrentPage = True
                 PrintDialog1.AllowSomePages = True
                 PrintDialog1.ShowDialog()
            
            
             End Sub
          Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
                 Timer1.Stop()
                 Dim ppd As New PrintPreviewDialogWithPrinter
                 
                 
            
                 ppd.Document = PrintDocument1
                 PrintDocument1.DefaultPageSettings.Landscape = True
            
                 PrintDialog1.Document = PrintDocument1
            
                 CType(ppd.Controls(1), ToolStrip).Items.Add(PDB)
                 ppd.WindowState = FormWindowState.Maximized
                 ppd.ShowDialog()
                 Me.Close()
                 
             End Sub

  2. #2
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,059

    Re: How to select the page number to print in print preview dialog box?

    The PrintDialog allows you to select pages, but you have to write the actual print range stuff in your PrintDocument1_PrintPage. If you just have the code for the full range of pages there, then that’s what it’ll print…

  3. #3
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,059

    Re: How to select the page number to print in print preview dialog box?

    You need to write conditionals which allow a certain part of the full range to be printed. The PrintDialog provides a UI to allow selection, then in your PrintDocument, you need to use that selection to restrict the full range printing to just those pages selected…

  4. #4

    Thread Starter
    Lively Member
    Join Date
    Mar 2019
    Posts
    85

    Re: How to select the page number to print in print preview dialog box?

    thanks for your help and for me the problem is how i can get the number that entered in PrintDialog ui so i can use it in 'For p As Integer = startPage To pages.Count - 1'
    i will make a condition to change the pages.count-1 to the entered value
    pages.Count - 1= new value
    also in click print button not printing only print when i click the icon print in PrintPreviewDialogWithPrinter
    in the print dialog button not printing
    please help

  5. #5
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    109,268

    Re: How to select the page number to print in print preview dialog box?

    It's in the documentation:

    https://learn.microsoft.com/en-au/do...ngs-printrange

    If PrintRange is PrintRange.SomePages, use the FromPage and ToPage properties to determine what pages should be printed.

  6. #6
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    109,268

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by houssem View Post
    thanks for your help and for me the problem is how i can get the number that entered in PrintDialog ui so i can use it in 'For p As Integer = startPage To pages.Count - 1'
    That would be wrong. You don't use a loop when printing. The PrintPage event is raised and you print a page, then you set e.HasMorePages if there are more pages to print. If you are printing a range then you should keep a count of how many pages have been printed and when that count plus FromPage is equal to ToPage then there are no more pages to print, so you set e.HasMorePages to False.

  7. #7

    Thread Starter
    Lively Member
    Join Date
    Mar 2019
    Posts
    85

    Re: How to select the page number to print in print preview dialog box?

    PrintDialog1.AllowSomePages = True
    'my measures tells that there are 10 pages, display this initial range
    PrintDocument1.PrinterSettings.FromPage = 1
    PrintDocument1.PrinterSettings.ToPage = 10

    'show dialog
    If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
    'get the settings from dialog
    PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings
    'print
    PrintDocument1.Print()
    End If
    the print setting not getting those number and also i want get it from the textbox
    please help

  8. #8
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    109,268

    Re: How to select the page number to print in print preview dialog box?

    Why would you be setting the FromPage and ToPage? The whole point is to let the user decide what pages to print.

    Apart from that, as you have already been told, it's up to you to use that information and only print those pages. It's not going to happen on its own. .paul. already told you that and you seem to have just ignored it. E.g.
    vb.net Code:
    1. Private printedPageCount As Integer
    2.  
    3. Private Sub PrintDocument1_BeginPrint(sender As Object, e As PrintEventArgs) Handles PrintDocument1.BeginPrint
    4.     printedPageCount = 0
    5. End Sub
    6.  
    7. Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
    8.     Dim pageNumber As Integer
    9.  
    10.     If e.PageSettings.PrinterSettings.PrintRange = PrintRange.SomePages Then
    11.         pageNumber = e.PageSettings.PrinterSettings.FromPage + printedPageCount
    12.     Else
    13.         pageNumber = printedPageCount + 1
    14.     End If
    15.  
    16.     'Print the page with the appropriate number here.
    17.  
    18.     printedPageCount += 1
    19.  
    20.     If e.PageSettings.PrinterSettings.PrintRange = PrintRange.SomePages Then
    21.         e.HasMorePages = (e.PageSettings.PrinterSettings.FromPage + printedPageCount > e.PageSettings.PrinterSettings.ToPage)
    22.     Else
    23.         'Use appropriate calculation to set e.HasMorePages here.
    24.     End If
    25. End Sub

  9. #9
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,059

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by jmcilhinney View Post
    That would be wrong. You don't use a loop when printing. The PrintPage event is raised and you print a page, then you set e.HasMorePages if there are more pages to print. If you are printing a range then you should keep a count of how many pages have been printed and when that count plus FromPage is equal to ToPage then there are no more pages to print, so you set e.HasMorePages to False.
    It might sound weird to jmcilhinney, but I would use a loop as you mentioned. It wouldn’t be traditional loop behaviour as you’d start at startpage and only execute the code in one pass of the loop, setting startpage to the next page number and exiting before looping.
    After that you either set e.hasmorepages to true and exit printpage so it will run again and print the next page, or selection has been printed and you’d just allow execution to exit printpage…

  10. #10
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    109,268

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by .paul. View Post
    It might sound weird to jmcilhinney, but I would use a loop as you mentioned. It wouldn’t be traditional loop behaviour as you’d start at startpage and only execute the code in one pass of the loop, setting startpage to the next page number and exiting before looping.
    It's certainly not impossible to use a loop - always multiple ways to skin a cat - but anything I'm imagining would not be my preferred method. Seems a less than optimal way to increment a variable.

  11. #11
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,059

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by jmcilhinney View Post
    It's certainly not impossible to use a loop - always multiple ways to skin a cat - but anything I'm imagining would not be my preferred method. Seems a less than optimal way to increment a variable.
    The best and optimal way to print multiple pages, depends a lot on what you’re trying to print…

  12. #12
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    109,268

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by .paul. View Post
    The best and optimal way to print multiple pages, depends a lot on what you’re trying to print…
    That's a fair point. If you're building the output as you go then I can see a need to process the data not being printed, so I guess a loop that do so and discards all but the next page to actually print might be useful.

  13. #13

    Thread Starter
    Lively Member
    Join Date
    Mar 2019
    Posts
    85

    Re: How to select the page number to print in print preview dialog box?

    i still can't understand how i will change the range of printing operation
    using this i can get the start page and the final page to print
    Code:
    Private printedPageCount As Integer
     
    Private Sub PrintDocument1_BeginPrint(sender As Object, e As PrintEventArgs) Handles PrintDocument1.BeginPrint
        printedPageCount = 0
    End Sub
     
    Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim pageNumber As Integer
     
        If e.PageSettings.PrinterSettings.PrintRange = PrintRange.SomePages Then
            pageNumber = e.PageSettings.PrinterSettings.FromPage + printedPageCount
    
    ////////////////////////////////////////////////////////////////////////////
                startPage = e.PageSettings.PrinterSettings.FromPage???
    
    
    
    /////////////////////////////////////////////////////////////////////////////
    
    
    
            For p As Integer = startPage To pages.Count - 1
                'If startPage = p Then
                'Dim num As Integer
                'num = p + 1
                Label15.Text = "Page N° " & p + 1 & "/" & pages.Count
                Dim rect2 = New Rectangle(690, 1122, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Label15.Height)
                e.Graphics.DrawString(Label15.Text, Label15.Font, Brushes.Black, rect2, sf2)
    
    
    
                'End If
                Dim cell As New Rectangle(startX, startY, DataGridView1.RowHeadersWidth, DataGridView1.ColumnHeadersHeight)
                e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                e.Graphics.DrawRectangle(Pens.Black, cell)
                startY += DataGridView1.ColumnHeadersHeight
                For r As Integer = pages(p).startRow To pages(p).startRow + pages(p).rows - 1
                    cell = New Rectangle(startX, startY, DataGridView1.RowHeadersWidth, DataGridView1.Rows(r).Height)
                    e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                    e.Graphics.DrawRectangle(Pens.Black, cell)
                    e.Graphics.DrawString(DataGridView1.Rows(r).HeaderCell.Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                    startY += DataGridView1.Rows(r).Height
                Next
    
                startX += cell.Width
                startY = rect.Bottom + 20
                For c As Integer = pages(p).startCol To pages(p).startCol + pages(p).columns - 1
                    cell = New Rectangle(startX, startY, DataGridView1.Columns(c).Width, DataGridView1.ColumnHeadersHeight)
                    e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                    e.Graphics.DrawRectangle(Pens.Black, cell)
                    e.Graphics.DrawString(DataGridView1.Columns(c).HeaderCell.Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                    startX += DataGridView1.Columns(c).Width
                Next
    
                startY = rect.Bottom + DataGridView1.ColumnHeadersHeight + 20
    
                For r As Integer = pages(p).startRow To pages(p).startRow + pages(p).rows - 1
                    startX = 50 + DataGridView1.RowHeadersWidth
                    For c As Integer = pages(p).startCol To pages(p).startCol + pages(p).columns - 1
                        cell = New Rectangle(startX, startY, DataGridView1.Columns(c).Width, DataGridView1.Rows(r).Height)
                        e.Graphics.DrawRectangle(Pens.Black, cell)
                        If DataGridView1.Columns(c).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight Then
                            sf.Alignment = StringAlignment.Near
                        Else
                            sf.Alignment = StringAlignment.Near
                        End If
                        e.Graphics.DrawString(DataGridView1(c, r).Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                        startX += DataGridView1.Columns(c).Width
                    Next
                    startY += DataGridView1.Rows(r).Height
                Next
                If p <> pages.Count - 1 Then
                    startPage = p + 1
                    e.HasMorePages = True
                    Return
                Else
            startPage = 0
                End If
    
    Next
    
    
    
    
    
    
        Else
            pageNumber = printedPageCount + 1
        End If
     
        'Print the page with the appropriate number here.
     
        printedPageCount += 1
     
        If e.PageSettings.PrinterSettings.PrintRange = PrintRange.SomePages Then
            e.HasMorePages = (e.PageSettings.PrinterSettings.FromPage + printedPageCount > e.PageSettings.PrinterSettings.ToPage)
        Else
            'Use appropriate calculation to set e.HasMorePages here.
        End If
    End Sub

  14. #14
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    109,268

    Re: How to select the page number to print in print preview dialog box?

    I put this comment in the code that you apparently copied and then ignored:
    'Print the page with the appropriate number here.
    What part of that is confusing you?

  15. #15

    Thread Starter
    Lively Member
    Join Date
    Mar 2019
    Posts
    85

    Re: How to select the page number to print in print preview dialog box?

    i'am confused on how i will using all the variable and understanding them properly like
    printedPageCount : apparently count the number of page to be printed.
    pageNumber : looks like its the first page to begin print and it has incrementation so that will get a condition with e.HasMorePages that will return false if the counter reach the final page .
    e.HasMorePages = (e.PageSettings.PrinterSettings.FromPage + printedPageCount > e.PageSettings.PrinterSettings.ToPage) : this will return false if reach the final page and
    Else
    'Use appropriate calculation to set e.HasMorePages here.
    End If
    what calculation if e.HasMorePages has the condition to be true or false

    and what in my head and thinking of :

    e.PageSettings.PrinterSettings.FromPage : the start page to print and i've test it and work but only print this page not incremented to next page which range i choose always print the first page only.
    pages.Count - 1 : how i raplace this with the final page to be printed which iget using e.PageSettings.PrinterSettings.ToPage and i can't use it because it should loop the pages not anything else so that i get the next page etc.
    If p <> pages.Count - 1 Then
    startPage = p + 1
    e.HasMorePages = True
    Return
    Else
    startPage = 0
    End If
    this probably the condition where it increment the startPage and print page one by one and i need to replace it with same idea but only the range of page to be printed and if reach the limit that will
    return e.HasMorePages = False.

  16. #16
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,059

    Re: How to select the page number to print in print preview dialog box?

    What are you trying to print? What controls?

  17. #17
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    109,268

    Re: How to select the page number to print in print preview dialog box?

    You're really making a meal of something that is relatively simple. The code I provided in post #8 can be used pretty much as is. All you had to do was replace these comments:
    Code:
    'Print the page with the appropriate number here.
    Code:
    'Use appropriate calculation to set e.HasMorePages here.
    In my code, printedPageCount is the count of pages that have been printed and pageNumber is the number of the page currently being printed. I would suggest that the first step from there should be write methods that can be called from the locations of those comments and then calling them:
    vb.net Code:
    1. 'The count of the pages already printed.
    2. Private printedPageCount As Integer
    3.  
    4. Private Sub PrintDocument1_BeginPrint(sender As Object, e As PrintEventArgs) Handles PrintDocument1.BeginPrint
    5.     printedPageCount = 0
    6. End Sub
    7.  
    8. Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
    9.     'The 1-based number of the page currently being printed.
    10.     Dim pageNumber As Integer
    11.  
    12.     If e.PageSettings.PrinterSettings.PrintRange = PrintRange.SomePages Then
    13.         pageNumber = e.PageSettings.PrinterSettings.FromPage + printedPageCount
    14.     Else
    15.         pageNumber = printedPageCount + 1
    16.     End If
    17.  
    18.     'Print the page with the appropriate number here.
    19.     PrintPage(pageNumber, e.Graphics)
    20.  
    21.     printedPageCount += 1
    22.  
    23.     If e.PageSettings.PrinterSettings.PrintRange = PrintRange.SomePages Then
    24.         e.HasMorePages = (e.PageSettings.PrinterSettings.FromPage + printedPageCount <= e.PageSettings.PrinterSettings.ToPage)
    25.     Else
    26.         'Use appropriate calculation to set e.HasMorePages here.
    27.         e.HasMorePages = HasMorePages(pageNumber)
    28.     End If
    29. End Sub
    30.  
    31. Private Sub PrintPage(pageNumber As Integer, g As Graphics)
    32.     Throw New NotImplementedException
    33. End Sub
    34.  
    35. Private Function HasMorePages(pageNumber As Integer) As Boolean
    36.     Throw New NotImplementedException
    37. End Function
    Note that I did notice a mistake in my original code. I originally had this:
    vb.net Code:
    1. e.HasMorePages = (e.PageSettings.PrinterSettings.FromPage + printedPageCount > e.PageSettings.PrinterSettings.ToPage)
    when it should have been this:
    vb.net Code:
    1. e.HasMorePages = (e.PageSettings.PrinterSettings.FromPage + printedPageCount <= e.PageSettings.PrinterSettings.ToPage)
    Here is a simple example of how you might implement those methods. This uses a list of numbers that are printed 2 to a page:
    vb.net Code:
    1. Private ReadOnly items As Integer() = Enumerable.Range(1, 20).ToArray()
    2. Private Const itemsPerPage As Integer = 2
    3.  
    4. Private Sub PrintPage(pageNumber As Integer, g As Graphics)
    5.     Dim pageData = items.Skip((pageNumber - 1) * itemsPerPage).Take(itemsPerPage)
    6.     Dim y = 50
    7.  
    8.     For Each item In pageData
    9.         g.DrawString(item.ToString(), Font, Brushes.Black, 50, y)
    10.         y += 50
    11.     Next
    12. End Sub
    13.  
    14. Private Function HasMorePages(pageNumber As Integer) As Boolean
    15.     Dim totalPageCount = CInt(Math.Ceiling(items.Length / itemsPerPage))
    16.  
    17.     Return pageNumber < totalPageCount
    18. End Function
    I then tested that using this code:
    vb.net Code:
    1. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    2.     With PrintDocument1.DefaultPageSettings.PrinterSettings
    3.         .PrintRange = PrintRange.SomePages
    4.         .FromPage = 3
    5.         .ToPage = 6
    6.     End With
    7.  
    8.     PrintPreviewDialog1.ShowDialog()
    9. End Sub
    Sure enough, I saw four pages previewed containing the numbers 5 & 6, 7 & 8, 9 & 10 and 11 & 12.

    You need to apply that same logic to whatever data you are printing. Pull out the data for the current pageNumber and print where I said to and then calculate whether there are more pages print based on the total number of pages and the number of pages already printed where I said to.

  18. #18
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,059

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by houssem View Post
    i still can't understand how i will change the range of printing operation
    using this i can get the start page and the final page to print
    Code:
    Private printedPageCount As Integer
     
    Private Sub PrintDocument1_BeginPrint(sender As Object, e As PrintEventArgs) Handles PrintDocument1.BeginPrint
    
        printedPageCount = 0
    End Sub
     
    Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim pageNumber As Integer
     
        If e.PageSettings.PrinterSettings.PrintRange = PrintRange.SomePages Then
            pageNumber = e.PageSettings.PrinterSettings.FromPage + printedPageCount
    
    ////////////////////////////////////////////////////////////////////////////
                startPage = e.PageSettings.PrinterSettings.FromPage???
    
    
    
    /////////////////////////////////////////////////////////////////////////////
    
    
    
            For p As Integer = startPage To pages.Count - 1
                'If startPage = p Then
                'Dim num As Integer
                'num = p + 1
                Label15.Text = "Page N° " & p + 1 & "/" & pages.Count
                Dim rect2 = New Rectangle(690, 1122, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Label15.Height)
                e.Graphics.DrawString(Label15.Text, Label15.Font, Brushes.Black, rect2, sf2)
    
    
    
                'End If
                Dim cell As New Rectangle(startX, startY, DataGridView1.RowHeadersWidth, DataGridView1.ColumnHeadersHeight)
                e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                e.Graphics.DrawRectangle(Pens.Black, cell)
                startY += DataGridView1.ColumnHeadersHeight
                For r As Integer = pages(p).startRow To pages(p).startRow + pages(p).rows - 1
                    cell = New Rectangle(startX, startY, DataGridView1.RowHeadersWidth, DataGridView1.Rows(r).Height)
                    e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                    e.Graphics.DrawRectangle(Pens.Black, cell)
                    e.Graphics.DrawString(DataGridView1.Rows(r).HeaderCell.Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                    startY += DataGridView1.Rows(r).Height
                Next
    
                startX += cell.Width
                startY = rect.Bottom + 20
                For c As Integer = pages(p).startCol To pages(p).startCol + pages(p).columns - 1
                    cell = New Rectangle(startX, startY, DataGridView1.Columns(c).Width, DataGridView1.ColumnHeadersHeight)
                    e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                    e.Graphics.DrawRectangle(Pens.Black, cell)
                    e.Graphics.DrawString(DataGridView1.Columns(c).HeaderCell.Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                    startX += DataGridView1.Columns(c).Width
                Next
    
                startY = rect.Bottom + DataGridView1.ColumnHeadersHeight + 20
    
                For r As Integer = pages(p).startRow To pages(p).startRow + pages(p).rows - 1
                    startX = 50 + DataGridView1.RowHeadersWidth
                    For c As Integer = pages(p).startCol To pages(p).startCol + pages(p).columns - 1
                        cell = New Rectangle(startX, startY, DataGridView1.Columns(c).Width, DataGridView1.Rows(r).Height)
                        e.Graphics.DrawRectangle(Pens.Black, cell)
                        If DataGridView1.Columns(c).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight Then
                            sf.Alignment = StringAlignment.Near
                        Else
                            sf.Alignment = StringAlignment.Near
                        End If
                        e.Graphics.DrawString(DataGridView1(c, r).Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                        startX += DataGridView1.Columns(c).Width
                    Next
                    startY += DataGridView1.Rows(r).Height
                Next
                If p <> pages.Count - 1 Then
                    startPage = p + 1
                    e.HasMorePages = True
                    Return
                Else
            startPage = 0
                End If
    
    Next
    
    
    
    
    
    
        Else
            pageNumber = printedPageCount + 1
        End If
     
        'Print the page with the appropriate number here.
     
        printedPageCount += 1
     
        If e.PageSettings.PrinterSettings.PrintRange = PrintRange.SomePages Then
            e.HasMorePages = (e.PageSettings.PrinterSettings.FromPage + printedPageCount > e.PageSettings.PrinterSettings.ToPage)
        Else
            'Use appropriate calculation to set e.HasMorePages here.
        End If
    End Sub
    Now I know what you’re doing. That looks like my multi page dgv printer code that you’re trying to modify…

    Code:
     startPage = e.PageSettings.PrinterSettings.FromPage
    endPage = e.PageSettings.PrinterSettings.ToPage
    
    
    
    /////////////////////////////////////////////////////////////////////////////
    
    
    
            For p As Integer = startPage To endPage - 1
    
    
    /////////////////////////////////////////////////////////////////////////////
    Last edited by .paul.; Nov 11th, 2022 at 03:48 AM.

  19. #19
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,059

    Re: How to select the page number to print in print preview dialog box?

    Try this... You need to be sure FromPage and ToPage are always set correctly starting at page 1 (or 2 or 3, not zero based)... etc...

    Code:
    Private printedPageCount As Integer
        Private startPage As Integer
        Private endPage As Integer
    
        Private Sub PrintDocument1_BeginPrint(ByVal sender As Object, ByVal e As PrintEventArgs) Handles PrintDocument1.BeginPrint
            If e.PageSettings.PrinterSettings.PrintRange = PrintRange.SomePages Then
                ' check FromPage and ToPage are set to appropriate values
                startPage = e.PageSettings.PrinterSettings.FromPage
                endPage = e.PageSettings.PrinterSettings.ToPage
            Else
                startPage = 1
                endPage = pages.count
            End If
            printedPageCount = 0
        End Sub
    
        Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
            Dim pageNumber As Integer
    
            For p As Integer = startPage - 1 To endPage - 1
                'If startPage = p Then
                'Dim num As Integer
                'num = p + 1
                Label15.Text = "Page N° " & p + 1 & "/" & pages.Count
                Dim rect2 = New Rectangle(690, 1122, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Label15.Height)
                e.Graphics.DrawString(Label15.Text, Label15.Font, Brushes.Black, rect2, sf2)
    
    
    
                'End If
                Dim cell As New Rectangle(startX, startY, DataGridView1.RowHeadersWidth, DataGridView1.ColumnHeadersHeight)
                e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                e.Graphics.DrawRectangle(Pens.Black, cell)
                startY += DataGridView1.ColumnHeadersHeight
                For r As Integer = pages(p).startRow To pages(p).startRow + pages(p).rows - 1
                    cell = New Rectangle(startX, startY, DataGridView1.RowHeadersWidth, DataGridView1.Rows(r).Height)
                    e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                    e.Graphics.DrawRectangle(Pens.Black, cell)
                    e.Graphics.DrawString(DataGridView1.Rows(r).HeaderCell.Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                    startY += DataGridView1.Rows(r).Height
                Next
    
                startX += cell.Width
                startY = rect.Bottom + 20
                For c As Integer = pages(p).startCol To pages(p).startCol + pages(p).columns - 1
                    cell = New Rectangle(startX, startY, DataGridView1.Columns(c).Width, DataGridView1.ColumnHeadersHeight)
                    e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                    e.Graphics.DrawRectangle(Pens.Black, cell)
                    e.Graphics.DrawString(DataGridView1.Columns(c).HeaderCell.Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                    startX += DataGridView1.Columns(c).Width
                Next
    
                startY = rect.Bottom + DataGridView1.ColumnHeadersHeight + 20
    
                For r As Integer = pages(p).startRow To pages(p).startRow + pages(p).rows - 1
                    startX = 50 + DataGridView1.RowHeadersWidth
                    For c As Integer = pages(p).startCol To pages(p).startCol + pages(p).columns - 1
                        cell = New Rectangle(startX, startY, DataGridView1.Columns(c).Width, DataGridView1.Rows(r).Height)
                        e.Graphics.DrawRectangle(Pens.Black, cell)
                        If DataGridView1.Columns(c).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight Then
                            sf.Alignment = StringAlignment.Near
                        Else
                            sf.Alignment = StringAlignment.Near
                        End If
                        e.Graphics.DrawString(DataGridView1(c, r).Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                        startX += DataGridView1.Columns(c).Width
                    Next
                    startY += DataGridView1.Rows(r).Height
                Next
                If p <> endPage - 1 Then
                    startPage = p + 1
                    e.HasMorePages = True
                    Return '***ooops - edited here***
                Else
                    startPage = 1
                End If
    
            Next
    End Sub
    Last edited by .paul.; Nov 12th, 2022 at 03:09 AM.

  20. #20

    Thread Starter
    Lively Member
    Join Date
    Mar 2019
    Posts
    85

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by .paul. View Post
    Try this... You need to be sure FromPage and ToPage are always set correctly starting at page 1 (or 2 or 3, not zero based)... etc...

    Code:
    Private printedPageCount As Integer
        Private startPage As Integer
        Private endPage As Integer
    
        Private Sub PrintDocument1_BeginPrint(ByVal sender As Object, ByVal e As PrintEventArgs) Handles PrintDocument1.BeginPrint
            If e.PageSettings.PrinterSettings.PrintRange = PrintRange.SomePages Then
                ' check FromPage and ToPage are set to appropriate values
                startPage = e.PageSettings.PrinterSettings.FromPage
                endPage = e.PageSettings.PrinterSettings.ToPage
            Else
                startPage = 1
                endPage = pages.count
            End If
            printedPageCount = 0
        End Sub
    
        Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
            Dim pageNumber As Integer
    
            For p As Integer = startPage - 1 To endPage - 1
                'If startPage = p Then
                'Dim num As Integer
                'num = p + 1
                Label15.Text = "Page N° " & p + 1 & "/" & pages.Count
                Dim rect2 = New Rectangle(690, 1122, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Label15.Height)
                e.Graphics.DrawString(Label15.Text, Label15.Font, Brushes.Black, rect2, sf2)
    
    
    
                'End If
                Dim cell As New Rectangle(startX, startY, DataGridView1.RowHeadersWidth, DataGridView1.ColumnHeadersHeight)
                e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                e.Graphics.DrawRectangle(Pens.Black, cell)
                startY += DataGridView1.ColumnHeadersHeight
                For r As Integer = pages(p).startRow To pages(p).startRow + pages(p).rows - 1
                    cell = New Rectangle(startX, startY, DataGridView1.RowHeadersWidth, DataGridView1.Rows(r).Height)
                    e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                    e.Graphics.DrawRectangle(Pens.Black, cell)
                    e.Graphics.DrawString(DataGridView1.Rows(r).HeaderCell.Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                    startY += DataGridView1.Rows(r).Height
                Next
    
                startX += cell.Width
                startY = rect.Bottom + 20
                For c As Integer = pages(p).startCol To pages(p).startCol + pages(p).columns - 1
                    cell = New Rectangle(startX, startY, DataGridView1.Columns(c).Width, DataGridView1.ColumnHeadersHeight)
                    e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                    e.Graphics.DrawRectangle(Pens.Black, cell)
                    e.Graphics.DrawString(DataGridView1.Columns(c).HeaderCell.Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                    startX += DataGridView1.Columns(c).Width
                Next
    
                startY = rect.Bottom + DataGridView1.ColumnHeadersHeight + 20
    
                For r As Integer = pages(p).startRow To pages(p).startRow + pages(p).rows - 1
                    startX = 50 + DataGridView1.RowHeadersWidth
                    For c As Integer = pages(p).startCol To pages(p).startCol + pages(p).columns - 1
                        cell = New Rectangle(startX, startY, DataGridView1.Columns(c).Width, DataGridView1.Rows(r).Height)
                        e.Graphics.DrawRectangle(Pens.Black, cell)
                        If DataGridView1.Columns(c).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight Then
                            sf.Alignment = StringAlignment.Near
                        Else
                            sf.Alignment = StringAlignment.Near
                        End If
                        e.Graphics.DrawString(DataGridView1(c, r).Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                        startX += DataGridView1.Columns(c).Width
                    Next
                    startY += DataGridView1.Rows(r).Height
                Next
                If p <> endPage - 1 Then
                    startPage = p + 1
                    e.HasMorePages = True
                    Return '***ooops - edited here***
                Else
                    startPage = 1
                End If
    
            Next
    End Sub
    i get error in this code
    Private Sub PrintDocument1_BeginPrint(ByVal sender As Object, ByVal e As PrintEventArgs) Handles PrintDocument1.BeginPrint
    If e.PageSettings.PrinterSettings.PrintRange = PrintRange.SomePages Then
    ' check FromPage and ToPage are set to appropriate values
    startPage = e.PageSettings.PrinterSettings.FromPage
    endPage = e.PageSettings.PrinterSettings.ToPage
    Else
    startPage = 1
    endPage = pages.count
    End If
    printedPageCount = 0
    End Sub

  21. #21
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,059

    Re: How to select the page number to print in print preview dialog box?

    Code:
    Private Sub PrintDocument1_BeginPrint(ByVal sender As Object, ByVal e As PrintEventArgs) Handles PrintDocument1.BeginPrint
        Dim ps As New PrintDialog
    
        If ps.ShowDialog = DialogResult.OK Then
            If ps.PrinterSettings.PrintRange = PrintRange.SomePages Then
                ' check FromPage and ToPage are set to appropriate values
                startPage = ps.PrinterSettings.FromPage
                endPage = ps.PrinterSettings.ToPage
            Else
                startPage = 1
                endPage = pages.count
            End If
        Else
            e.Cancel = True
        End If
        printedPageCount = 0
    End Sub

  22. #22

    Thread Starter
    Lively Member
    Join Date
    Mar 2019
    Posts
    85

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by .paul. View Post
    Code:
    Private Sub PrintDocument1_BeginPrint(ByVal sender As Object, ByVal e As PrintEventArgs) Handles PrintDocument1.BeginPrint
        Dim ps As New PrintDialog
    
        If ps.ShowDialog = DialogResult.OK Then
            If ps.PrinterSettings.PrintRange = PrintRange.SomePages Then
                ' check FromPage and ToPage are set to appropriate values
                startPage = ps.PrinterSettings.FromPage
                endPage = ps.PrinterSettings.ToPage
            Else
                startPage = 1
                endPage = pages.count
            End If
        Else
            e.Cancel = True
        End If
        printedPageCount = 0
    End Sub
    i forget to mention that i've added a button in PrintPreviewDialog that all the work on it
    i called choose a printer from there the dialog appear and change from all page to print to a range of page
    because of this code i talked about
    If ps.ShowDialog = DialogResult.OK Then
    If ps.PrinterSettings.PrintRange = PrintRange.SomePages Then
    ' check FromPage and ToPage are set to appropriate values
    startPage = ps.PrinterSettings.FromPage
    endPage = ps.PrinterSettings.ToPage
    Else
    startPage = 1
    endPage = pages.count
    End If
    Else
    e.Cancel = True
    End If
    this code should be in the button event
    Code:
     Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
            Timer1.Stop()
            Dim ppd As New PrintPreviewDialogWithPrinter
    
    
    
            PrintDocument1.DefaultPageSettings.Landscape = True
            PrintDialog1.AllowSelection = True
            PrintDialog1.AllowCurrentPage = True
            PrintDialog1.AllowSomePages = True
            PrintDialog1.Document = PrintDocument1
            ppd.Document = PrintDocument1
            CType(ppd.Controls(1), ToolStrip).Items.Add(PDB)
            ppd.WindowState = FormWindowState.Maximized
    
            ppd.ShowDialog()
    
            Me.Close()
    
        End Sub
    
        Private WithEvents PDB As New ToolStripButton("Choisie une imprimante")
    
        Private Sub PDB_Click1(ByVal sender As Object, ByVal e As EventArgs) Handles PDB.Click
            PrintDialog1.AllowSelection = True
            PrintDialog1.AllowCurrentPage = True
    
            PrintDialog1.AllowSomePages = True
    
            PrintDocument1.PrinterSettings.PrintRange = Drawing.Printing.PrintRange.SomePages
            PrintDocument1.PrinterSettings.FromPage = 2
            PrintDocument1.PrinterSettings.ToPage = 4
    
            If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
    
                PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings
    
                PrintDocument1.Print()
            End If
    
    
    
            Me.Close()
    
    
    
        End Sub

  23. #23

    Thread Starter
    Lively Member
    Join Date
    Mar 2019
    Posts
    85

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by jmcilhinney View Post
    You're really making a meal of something that is relatively simple. The code I provided in post #8 can be used pretty much as is. All you had to do was replace these comments:
    Code:
    'Print the page with the appropriate number here.
    Code:
    'Use appropriate calculation to set e.HasMorePages here.
    In my code, printedPageCount is the count of pages that have been printed and pageNumber is the number of the page currently being printed. I would suggest that the first step from there should be write methods that can be called from the locations of those comments and then calling them:
    vb.net Code:
    1. 'The count of the pages already printed.
    2. Private printedPageCount As Integer
    3.  
    4. Private Sub PrintDocument1_BeginPrint(sender As Object, e As PrintEventArgs) Handles PrintDocument1.BeginPrint
    5.     printedPageCount = 0
    6. End Sub
    7.  
    8. Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
    9.     'The 1-based number of the page currently being printed.
    10.     Dim pageNumber As Integer
    11.  
    12.     If e.PageSettings.PrinterSettings.PrintRange = PrintRange.SomePages Then
    13.         pageNumber = e.PageSettings.PrinterSettings.FromPage + printedPageCount
    14.     Else
    15.         pageNumber = printedPageCount + 1
    16.     End If
    17.  
    18.     'Print the page with the appropriate number here.
    19.     PrintPage(pageNumber, e.Graphics)
    20.  
    21.     printedPageCount += 1
    22.  
    23.     If e.PageSettings.PrinterSettings.PrintRange = PrintRange.SomePages Then
    24.         e.HasMorePages = (e.PageSettings.PrinterSettings.FromPage + printedPageCount <= e.PageSettings.PrinterSettings.ToPage)
    25.     Else
    26.         'Use appropriate calculation to set e.HasMorePages here.
    27.         e.HasMorePages = HasMorePages(pageNumber)
    28.     End If
    29. End Sub
    30.  
    31. Private Sub PrintPage(pageNumber As Integer, g As Graphics)
    32.     Throw New NotImplementedException
    33. End Sub
    34.  
    35. Private Function HasMorePages(pageNumber As Integer) As Boolean
    36.     Throw New NotImplementedException
    37. End Function
    Note that I did notice a mistake in my original code. I originally had this:
    vb.net Code:
    1. e.HasMorePages = (e.PageSettings.PrinterSettings.FromPage + printedPageCount > e.PageSettings.PrinterSettings.ToPage)
    when it should have been this:
    vb.net Code:
    1. e.HasMorePages = (e.PageSettings.PrinterSettings.FromPage + printedPageCount <= e.PageSettings.PrinterSettings.ToPage)
    Here is a simple example of how you might implement those methods. This uses a list of numbers that are printed 2 to a page:
    vb.net Code:
    1. Private ReadOnly items As Integer() = Enumerable.Range(1, 20).ToArray()
    2. Private Const itemsPerPage As Integer = 2
    3.  
    4. Private Sub PrintPage(pageNumber As Integer, g As Graphics)
    5.     Dim pageData = items.Skip((pageNumber - 1) * itemsPerPage).Take(itemsPerPage)
    6.     Dim y = 50
    7.  
    8.     For Each item In pageData
    9.         g.DrawString(item.ToString(), Font, Brushes.Black, 50, y)
    10.         y += 50
    11.     Next
    12. End Sub
    13.  
    14. Private Function HasMorePages(pageNumber As Integer) As Boolean
    15.     Dim totalPageCount = CInt(Math.Ceiling(items.Length / itemsPerPage))
    16.  
    17.     Return pageNumber < totalPageCount
    18. End Function
    I then tested that using this code:
    vb.net Code:
    1. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    2.     With PrintDocument1.DefaultPageSettings.PrinterSettings
    3.         .PrintRange = PrintRange.SomePages
    4.         .FromPage = 3
    5.         .ToPage = 6
    6.     End With
    7.  
    8.     PrintPreviewDialog1.ShowDialog()
    9. End Sub
    Sure enough, I saw four pages previewed containing the numbers 5 & 6, 7 & 8, 9 & 10 and 11 & 12.

    You need to apply that same logic to whatever data you are printing. Pull out the data for the current pageNumber and print where I said to and then calculate whether there are more pages print based on the total number of pages and the number of pages already printed where I said to.
    thanks a lot and i need to understand that and it should take time i'll back to you soon

  24. #24

    Thread Starter
    Lively Member
    Join Date
    Mar 2019
    Posts
    85

    Re: How to select the page number to print in print preview dialog box?

    in this methode :
    Code:
    Private Sub PrintPage(pageNumber As Integer, g As Graphics)
        Throw New NotImplementedException
    End Sub
    i should add this code:
    Code:
     For p As Integer = startPage To pages.Count - 1
                'If startPage = p Then
                'Dim num As Integer
                'num = p + 1
                Label15.Text = "Page N° " & p + 1 & "/" & pages.Count
                Dim rect2 = New Rectangle(690, 1122, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Label15.Height)
                e.Graphics.DrawString(Label15.Text, Label15.Font, Brushes.Black, rect2, sf2)
    
    
    
                'End If
                Dim cell As New Rectangle(startX, startY, DataGridView1.RowHeadersWidth, DataGridView1.ColumnHeadersHeight)
                e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                e.Graphics.DrawRectangle(Pens.Black, cell)
                startY += DataGridView1.ColumnHeadersHeight
                For r As Integer = pages(p).startRow To pages(p).startRow + pages(p).rows - 1
                    cell = New Rectangle(startX, startY, DataGridView1.RowHeadersWidth, DataGridView1.Rows(r).Height)
                    e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                    e.Graphics.DrawRectangle(Pens.Black, cell)
                    e.Graphics.DrawString(DataGridView1.Rows(r).HeaderCell.Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                    startY += DataGridView1.Rows(r).Height
                Next
    
                startX += cell.Width
                startY = rect.Bottom + 20
                For c As Integer = pages(p).startCol To pages(p).startCol + pages(p).columns - 1
                    cell = New Rectangle(startX, startY, DataGridView1.Columns(c).Width, DataGridView1.ColumnHeadersHeight)
                    e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                    e.Graphics.DrawRectangle(Pens.Black, cell)
                    e.Graphics.DrawString(DataGridView1.Columns(c).HeaderCell.Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                    startX += DataGridView1.Columns(c).Width
                Next
    
                startY = rect.Bottom + DataGridView1.ColumnHeadersHeight + 20
    
                For r As Integer = pages(p).startRow To pages(p).startRow + pages(p).rows - 1
                    startX = 50 + DataGridView1.RowHeadersWidth
                    For c As Integer = pages(p).startCol To pages(p).startCol + pages(p).columns - 1
                        cell = New Rectangle(startX, startY, DataGridView1.Columns(c).Width, DataGridView1.Rows(r).Height)
                        e.Graphics.DrawRectangle(Pens.Black, cell)
                        If DataGridView1.Columns(c).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight Then
                            sf.Alignment = StringAlignment.Near
                        Else
                            sf.Alignment = StringAlignment.Near
                        End If
                        e.Graphics.DrawString(DataGridView1(c, r).Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                        startX += DataGridView1.Columns(c).Width
                    Next
                    startY += DataGridView1.Rows(r).Height
                Next
                If p <> pages.Count - 1 Then
                    startPage = p + 1
                    e.HasMorePages = True
                    Return
                Else
                    startPage = 0
                End If

  25. #25
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,059

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by houssem View Post
    i forget to mention that i've added a button in PrintPreviewDialog that all the work on it
    i called choose a printer from there the dialog appear and change from all page to print to a range of page
    because of this code i talked about
    If ps.ShowDialog = DialogResult.OK Then
    If ps.PrinterSettings.PrintRange = PrintRange.SomePages Then
    ' check FromPage and ToPage are set to appropriate values
    startPage = ps.PrinterSettings.FromPage
    endPage = ps.PrinterSettings.ToPage
    Else
    startPage = 1
    endPage = pages.count
    End If
    Else
    e.Cancel = True
    End If
    this code should be in the button event
    Code:
     Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
            Timer1.Stop()
            Dim ppd As New PrintPreviewDialogWithPrinter
    
    
    
            PrintDocument1.DefaultPageSettings.Landscape = True
            PrintDialog1.AllowSelection = True
            PrintDialog1.AllowCurrentPage = True
            PrintDialog1.AllowSomePages = True
            PrintDialog1.Document = PrintDocument1
            ppd.Document = PrintDocument1
            CType(ppd.Controls(1), ToolStrip).Items.Add(PDB)
            ppd.WindowState = FormWindowState.Maximized
    
            ppd.ShowDialog()
    
            Me.Close()
    
        End Sub
    
        Private WithEvents PDB As New ToolStripButton("Choisie une imprimante")
    
        Private Sub PDB_Click1(ByVal sender As Object, ByVal e As EventArgs) Handles PDB.Click
            PrintDialog1.AllowSelection = True
            PrintDialog1.AllowCurrentPage = True
    
            PrintDialog1.AllowSomePages = True
    
            PrintDocument1.PrinterSettings.PrintRange = Drawing.Printing.PrintRange.SomePages
            PrintDocument1.PrinterSettings.FromPage = 2
            PrintDocument1.PrinterSettings.ToPage = 4
    
            If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
    
                PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings
    
                PrintDocument1.Print()
            End If
    
    
    
            Me.Close()
    
    
    
        End Sub
    Why are you using a Timer???
    The last lot of code I gave you should work for you with a few simple modifications.

    This is how the PrintDocument works…

    You call PrintDocument.Print
    The _BeginPrint sub runs once. There you run the code that works out what to print on each page.
    You can show the PrintDialog in _BeginPrint to select a page range.
    Then just copy and paste the modified _PrintPage from post #19

  26. #26

    Thread Starter
    Lively Member
    Join Date
    Mar 2019
    Posts
    85

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by .paul. View Post
    Why are you using a Timer???
    The last lot of code I gave you should work for you with a few simple modifications.

    This is how the PrintDocument works…

    You call PrintDocument.Print
    The _BeginPrint sub runs once. There you run the code that works out what to print on each page.
    You can show the PrintDialog in _BeginPrint to select a page range.
    Then just copy and paste the modified _PrintPage from post #19
    i use a timer because when i open a form i need to fill all the data in the datagridview and labels and without seeing the form is opened and open the print preview dialog
    like when i click print button in the form it open a new form while has all the data needed and direct open the print preview dialog with those data in that form and i made it hidden.

    in post 19 it have to open a new dialogue
    If ps.ShowDialog = DialogResult.OK Then
    and the idea is make everything normal and add a new button in printpreviewdialog that i talked about in that button i let the user choose a printer and choose if he want a range of page
    so i need this to work in that button
    Last edited by houssem; Nov 14th, 2022 at 10:29 AM.

  27. #27

    Thread Starter
    Lively Member
    Join Date
    Mar 2019
    Posts
    85

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by .paul. View Post
    Why are you using a Timer???
    The last lot of code I gave you should work for you with a few simple modifications.

    This is how the PrintDocument works…

    You call PrintDocument.Print
    The _BeginPrint sub runs once. There you run the code that works out what to print on each page.
    You can show the PrintDialog in _BeginPrint to select a page range.
    Then just copy and paste the modified _PrintPage from post #19
    i got an error in this line
    For r As Integer = pages(p).startRow To pages(p).startRow + pages(p).rows - 1

    the error is 'The given key was missing from the dictionary.'
    this i think cause the endpage is not declared like the pages
    please help

  28. #28
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,059

    Re: How to select the page number to print in print preview dialog box?

    In _BeginPrint, the pages are calculated. If you omitted that part, there’s your problem
    Last edited by .paul.; Nov 15th, 2022 at 04:09 PM.

  29. #29

    Thread Starter
    Lively Member
    Join Date
    Mar 2019
    Posts
    85

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by .paul. View Post
    In _BeginPrint, the pages are calculated. If you omitted that part, there’s your problem
    Quote Originally Posted by .paul. View Post
    In _BeginPrint, the pages are calculated. If you omitted that part, there’s your problem
    i've done everything you said and when i click the print button i get this error
    System.Collections.Generic.KeyNotFoundException
    HResult=0x80131577
    Message=La clé donnée était absente du dictionnaire.
    Source=mscorlib
    Arborescence des appels de procédure :
    à System.Collections.Generic.Dictionary`2.get_Item(TKey key)
    à Listes_BL.PrintedForm.PrintDocument1_PrintPage(Object sender, PrintPageEventArgs e) dans C:\Users\m.houssem\source\repos\Listes BL\Listes BL\PrintedForm.vb :ligne 349
    à System.Drawing.Printing.PrintDocument.OnPrintPage(PrintPageEventArgs e)
    à System.Drawing.Printing.PrintDocument._OnPrintPage(PrintPageEventArgs e)
    à System.Drawing.Printing.PrintController.PrintLoop(PrintDocument document)
    à System.Drawing.Printing.PrintController.Print(PrintDocument document)
    à System.Drawing.Printing.PrintDocument.Print()
    à System.Windows.Forms.PrintPreviewControl.ComputePreview()
    à System.Windows.Forms.PrintPreviewControl.CalculatePageInfo()

    System.Collections.Generic.KeyNotFoundException : 'the given key was missing from the dictionary.'

  30. #30
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,059

    Re: How to select the page number to print in print preview dialog box?

    Can you post your _BeginPrint code? (The entire sub)

  31. #31

    Thread Starter
    Lively Member
    Join Date
    Mar 2019
    Posts
    85

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by .paul. View Post
    Can you post your _BeginPrint code? (The entire sub)
    Code:
     Private Sub PrintDocument1_BeginPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles PrintDocument1.BeginPrint
    
    
            PrintDocument1.OriginAtMargins = True
            PrintDocument1.DefaultPageSettings.Margins = New Drawing.Printing.Margins(0, 0, 0, 0)
            Dim ps As New PrintDialog
            ps.AllowSomePages = True
            If ps.ShowDialog = DialogResult.OK Then
                If ps.PrinterSettings.PrintRange = PrintRange.SomePages Then
                    ' check FromPage and ToPage are set to appropriate values
                    startPage = ps.PrinterSettings.FromPage
                    endPage = ps.PrinterSettings.ToPage
                Else
                    startPage = 1
                    endPage = pages.Count
                End If
            Else
                e.Cancel = True
            End If
    
    
            printedPageCount = 0
            pages = New Dictionary(Of Integer, pageDetails)
            Dim maxWidth As Integer = CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width) + 340
            Dim maxHeight As Integer = CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Height) - 380
            Dim pageCounter As Integer = 0
            pages.Add(pageCounter, New pageDetails)
            Dim columnCounter As Integer = 0
            Dim columnSum As Integer = DataGridView1.RowHeadersWidth
            For c As Integer = 0 To DataGridView1.Columns.Count - 1
                If columnSum + DataGridView1.Columns(c).Width < maxWidth Then
                    columnSum += DataGridView1.Columns(c).Width
                    columnCounter += 1
                Else
                    pages(pageCounter) = New pageDetails With {.columns = columnCounter, .rows = 0, .startCol = pages(pageCounter).startCol}
                    columnSum = DataGridView1.RowHeadersWidth + DataGridView1.Columns(c).Width
                    columnCounter = 1
                    pageCounter += 1
                    pages.Add(pageCounter, New pageDetails With {.startCol = c})
                End If
                If c = DataGridView1.Columns.Count - 1 Then
                    If pages(pageCounter).columns = 0 Then
                        pages(pageCounter) = New pageDetails With {.columns = columnCounter, .rows = 0, .startCol = pages(pageCounter).startCol}
                    End If
                End If
            Next
    
            maxPagesWide = pages.Keys.Max + 1
    
            pageCounter = 0
    
            Dim rowCounter As Integer = 0
    
            Dim rowSum As Integer = DataGridView1.ColumnHeadersHeight
    
            For r As Integer = 0 To DataGridView1.Rows.Count - 2
                If rowSum + DataGridView1.Rows(r).Height < If(pageCounter = 0, maxHeight - (Lb1.Height + 75), maxHeight) Then
                    rowSum += DataGridView1.Rows(r).Height
                    rowCounter += 1
                Else
                    pages(pageCounter) = New pageDetails With {.columns = pages(pageCounter).columns, .rows = rowCounter, .startCol = pages(pageCounter).startCol, .startRow = pages(pageCounter).startRow}
                    For x As Integer = 1 To maxPagesWide - 1
                        pages(pageCounter + x) = New pageDetails With {.columns = pages(pageCounter + x).columns, .rows = rowCounter, .startCol = pages(pageCounter + x).startCol, .startRow = pages(pageCounter).startRow}
                    Next
    
                    pageCounter += maxPagesWide
                    For x As Integer = 0 To maxPagesWide - 1
                        pages.Add(pageCounter + x, New pageDetails With {.columns = pages(x).columns, .rows = 0, .startCol = pages(x).startCol, .startRow = r})
                    Next
    
                    rowSum = DataGridView1.ColumnHeadersHeight + DataGridView1.Rows(r).Height
                    rowCounter = 1
                End If
                If r = DataGridView1.Rows.Count - 2 Then
                    For x As Integer = 0 To maxPagesWide - 1
                        If pages(pageCounter + x).rows = 0 Then
                            pages(pageCounter + x) = New pageDetails With {.columns = pages(pageCounter + x).columns, .rows = rowCounter, .startCol = pages(pageCounter + x).startCol, .startRow = pages(pageCounter + x).startRow}
                        End If
                    Next
                End If
            Next
    
            maxPagesTall = pages.Count \ maxPagesWide
            pagecount = pageCounter
        End Sub

  32. #32
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,059

    Re: How to select the page number to print in print preview dialog box?

    Try moving this part of the code (below) to the end of the sub…

    Code:
    Dim ps As New PrintDialog
    ps.AllowSomePages = True
    If ps.ShowDialog = DialogResult.OK Then
        If ps.PrinterSettings.PrintRange = PrintRange.SomePages Then
            ‘ check FromPage and ToPage are set to appropriate values
            startPage = ps.PrinterSettings.FromPage
            endPage = ps.PrinterSettings.ToPage
        Else
            startPage = 1
            endPage = pages.Count
        End If
    Else
        e.Cancel = True
    End If

  33. #33

    Thread Starter
    Lively Member
    Join Date
    Mar 2019
    Posts
    85

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by .paul. View Post
    Try moving this part of the code (below) to the end of the sub…

    Code:
    Dim ps As New PrintDialog
    ps.AllowSomePages = True
    If ps.ShowDialog = DialogResult.OK Then
        If ps.PrinterSettings.PrintRange = PrintRange.SomePages Then
            ‘ check FromPage and ToPage are set to appropriate values
            startPage = ps.PrinterSettings.FromPage
            endPage = ps.PrinterSettings.ToPage
        Else
            startPage = 1
            endPage = pages.Count
        End If
    Else
        e.Cancel = True
    End If
    still the same error

  34. #34
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,059

    Re: How to select the page number to print in print preview dialog box?

    On which line is the error? You need to learn how to debug your code. The error is saying that the page number is not a valid key in the dictionary(of integer, pagedetails). If the pagenumber is less than 0 or greater than pages.count -1 it would cause that error.

    The dictionary contains keyvaluepairs. The key is the integer part. The value is an instance of pagedetails.

  35. #35

    Thread Starter
    Lively Member
    Join Date
    Mar 2019
    Posts
    85

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by .paul. View Post
    On which line is the error? You need to learn how to debug your code. The error is saying that the page number is not a valid key in the dictionary(of integer, pagedetails). If the pagenumber is less than 0 or greater than pages.count -1 it would cause that error.

    The dictionary contains keyvaluepairs. The key is the integer part. The value is an instance of pagedetails.
    the error
    Code:
      For r As Integer = pages(p).startRow To pages(p).startRow + pages(p).rows - 1
                    cell = New Rectangle(startX, startY, DataGridView1.RowHeadersWidth, DataGridView1.Rows(r).Height)
                    e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                    e.Graphics.DrawRectangle(Pens.Black, cell)
                    e.Graphics.DrawString(DataGridView1.Rows(r).HeaderCell.Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                    startY += DataGridView1.Rows(r).Height
                Next

  36. #36
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,059

    Re: How to select the page number to print in print preview dialog box?

    I checked my link. Seems broken. This is the Form I changed...

    Code:
    Imports System.Data.SqlClient
    Imports System.Drawing.Printing
    Imports Microsoft.VisualBasic.PowerPacks.Printing.Compatibility.VB6
    
    Public Class PrintedForm
    
        Dim cn As New SqlConnection("server=server;database=stupremat;integrated security=true")
        Dim cn1 As New SqlConnection("server=server;database=stupremat;integrated security=true")
        ' Dim cn As New SqlConnection("server='" & My.Settings.server & "';database='" & My.Settings.bd & "';integrated security=true")
    
        Dim ss2 As New DataTable
        Dim dt3 As New DataTable
        Dim totalPrix As Double
        Dim dt As New DataTable
        Dim dat As Decimal = 0
        Dim Fd As Decimal = 0
        Private Structure pageDetails
            Dim columns As Integer
            Dim rows As Integer
            Dim startCol As Integer
            Dim startRow As Integer
        End Structure
        ''' <summary>
        ''' dictionary to hold printed page details, with index key
        ''' </summary>
        ''' <remarks></remarks>
        Private pages As Dictionary(Of Integer, pageDetails)
    
        Dim maxPagesWide As Integer
        Dim maxPagesTall As Integer
        Private Sub PrintedForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
    
            Label3.Text = Date.Now.ToShortDateString
            'LbNum.Text = Form1.DataGridView1.CurrentRow.Cells(3).Value
            'DateSrt.Text = Date.Now.ToShortDateString
    
            '        If cn.State = ConnectionState.Open Then
            '            cn.Close()
            '        End If
            '        cn.Open()
    
            '        Dim cmdkk As New SqlCommand("SELECT top 200 F_COMPTET.CT_Intitule as Client,F_DOCENTETE.DO_Tiers as Code, F_DOCENTETE.DO_Date as Date, F_DOCENTETE.DO_Piece as Numero,cast( F_DOCENTETE.DO_TotalHT as real) as TotalHT
            ',cast( F_DOCENTETE.DO_TotalHTNet as real) as TotalHTNet,cast( F_DOCENTETE.DO_TotalTTC as real) as TotalTTC, F_COMPTET.CT_Contact as Contact, F_COMPTET.CT_Qualite as Qualite, F_DOCENTETE.DO_Ref as Ref, F_DOCENTETE.CA_Num as Num
            'FROM F_DOCENTETE INNER JOIN F_COMPTET ON F_DOCENTETE.DO_Tiers = F_COMPTET.CT_Num
            'WHERE ((F_DOCENTETE.do_type) =13) AND F_DOCENTETE.CA_Num<>'PAYER'
            'ORDER BY F_DOCENTETE.DO_Date desc", cn)
    
            '        Dim str77 As New SqlDataAdapter(cmdkk)
            '        Dim tab As New DataTable
    
            '        str77.Fill(tab)
    
            If Form1.listRechercher = True Then
                'MsgBox("ok222")
                ' [CT_EMail], CT_Adresse,[CT_Contact]
    
    
                For i = 0 To Form1.ListBox2.Items.Count - 1
                    TextBox1.Text &= Form1.ListBox2.Items(i).ToString & Environment.NewLine
    
                Next
                Label4.Text = ""
            Else
                TextBox1.Text = Form1.TextBox2.Text
                TextBox2.Text = ""
                TextBox3.Text = ""
                Label4.Text = ""
                Label5.Text = ""
            End If
            If Form1.codeRechercher = True Then
                Label4.Text = "Contact :"
            End If
            '    'MsgBox("ok")
            '    If cn.State = ConnectionState.Open Then
            '        cn.Close()
            '    End If
            '    cn.Open()
            '    Dim cmdkk22 As New SqlCommand("SELECT [CT_EMail], CT_Adresse,[CT_Contact]
    
            'from [F_COMPTET] where [CT_Num]='" & Form1.TextBox2.Text & "'", cn)
            '    Dim str772 As SqlDataReader = (cmdkk22.ExecuteReader)
            '    While str772.Read()
            TextBox2.Text = Form1.TextBox1.Text
    
            TextBox3.Text = Form1.TextBox4.Text
            Label5.Text = Form1.Label1.Text
            '    End While
            '    TextBox1.Text = Form1.TextBox2.Text
            'Else
    
            '    TextBox2.Text = ""
            '    TextBox3.Text = ""
            '    Label4.Text = ""
            '    Label5.Text = ""
            'End If
            'TextBox1.Text = Form1.ListBox2.DataSource
            'DataGridView1.Columns.Clear()
            'Dim tab As New DataTable
            'tab = Form1.DataGridView1.DataSource
            'DataGridView1.DataSource = Nothing
            'For i = 0 To tab.Rows.Count - 1
            '    'MsgBox(DataGridView1.Rows(i).Cells(2).Value.GetType.ToString)
            '    tab.Columns(2).DateTimeMode = DataGridView1.Rows(i).Cells(2).Value.ToString("yyyy/MM/dd")
            'Next
            'tab.Columns(2).DataType = GetType(Date)
            'DataGridView1.DataSource = tab
    
            '***For testing purposes only*******************************************
            For x As Integer = 0 To 10
                DataGridView1.Columns.Add(New DataGridViewTextBoxColumn)
            Next
            DataGridView1.Rows.Add(100)
            '***********************************************************************
    
    
            Dim var As DataGridViewColumn = DataGridView1.Columns(0)
            var.Width = 32
            Dim var6 As DataGridViewColumn = DataGridView1.Columns(1)
            var6.Width = 180
            Dim var7 As DataGridViewColumn = DataGridView1.Columns(2)
            var7.Width = 50
    
            Dim var8 As DataGridViewColumn = DataGridView1.Columns(3)
            var8.Width = 50
            Dim var3 As DataGridViewColumn = DataGridView1.Columns(4)
            var3.Width = 50
            Dim var4 As DataGridViewColumn = DataGridView1.Columns(5)
            var4.Width = 50
            Dim var5 As DataGridViewColumn = DataGridView1.Columns(6)
            var5.Width = 50
    
            Dim var2 As DataGridViewColumn = DataGridView1.Columns(9)
            var2.Width = 70
            Dim var9 As DataGridViewColumn = DataGridView1.Columns(7)
            var9.Width = 150
            Dim var10 As DataGridViewColumn = DataGridView1.Columns(8)
            var10.Width = 50
            Dim var11 As DataGridViewColumn = DataGridView1.Columns(10)
            var11.Width = 50
    
    
            For i = 0 To DataGridView1.Rows.Count - 1
                DataGridView1.Rows(i).HeaderCell.Value = i + 1
            Next
            
        End Sub
        ''@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
        Dim pagecount As Integer
        Private printedPageCount As Integer
        Private startPage As Integer
        Private endPage As Integer
        Private findingPages As Boolean
        Private Sub PrintDocument1_BeginPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles PrintDocument1.BeginPrint
    
    
            PrintDocument1.OriginAtMargins = True
            PrintDocument1.DefaultPageSettings.Margins = New Drawing.Printing.Margins(0, 0, 0, 0)
    
            '*****************************************************************************************************
            'If page is first page, you need to make allowances for your labels and strings you want to print here
            '*****************************************************************************************************
    
            printedPageCount = 0
            pages = New Dictionary(Of Integer, pageDetails)
            Dim maxWidth As Integer = CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width) '+ 340 ***This doesn't work. You need to allow pages besid and below the first page
            Dim maxHeight As Integer = CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Height) - 380
            Dim pageCounter As Integer = 0
            pages.Add(pageCounter, New pageDetails)
            Dim columnCounter As Integer = 0
            Dim columnSum As Integer = DataGridView1.RowHeadersWidth
            For c As Integer = 0 To DataGridView1.Columns.Count - 1
                If columnSum + DataGridView1.Columns(c).Width < maxWidth Then
                    columnSum += DataGridView1.Columns(c).Width
                    columnCounter += 1
                Else
                    pages(pageCounter) = New pageDetails With {.columns = columnCounter, .rows = 0, .startCol = pages(pageCounter).startCol}
                    columnSum = DataGridView1.RowHeadersWidth + DataGridView1.Columns(c).Width
                    columnCounter = 1
                    pageCounter += 1
                    pages.Add(pageCounter, New pageDetails With {.startCol = c})
                End If
                If c = DataGridView1.Columns.Count - 1 Then
                    If pages(pageCounter).columns = 0 Then
                        pages(pageCounter) = New pageDetails With {.columns = columnCounter, .rows = 0, .startCol = pages(pageCounter).startCol}
                    End If
                End If
            Next
    
            maxPagesWide = pages.Keys.Max + 1
    
            pageCounter = 0
    
            Dim rowCounter As Integer = 0
    
            Dim rowSum As Integer = DataGridView1.ColumnHeadersHeight
    
            For r As Integer = 0 To DataGridView1.Rows.Count - 2
                If rowSum + DataGridView1.Rows(r).Height < If(pageCounter = 0, maxHeight - (Lb1.Height + 75), maxHeight) Then
                    rowSum += DataGridView1.Rows(r).Height
                    rowCounter += 1
                Else
                    pages(pageCounter) = New pageDetails With {.columns = pages(pageCounter).columns, .rows = rowCounter, .startCol = pages(pageCounter).startCol, .startRow = pages(pageCounter).startRow}
                    For x As Integer = 1 To maxPagesWide - 1
                        pages(pageCounter + x) = New pageDetails With {.columns = pages(pageCounter + x).columns, .rows = rowCounter, .startCol = pages(pageCounter + x).startCol, .startRow = pages(pageCounter).startRow}
                    Next
    
                    pageCounter += maxPagesWide
                    For x As Integer = 0 To maxPagesWide - 1
                        pages.Add(pageCounter + x, New pageDetails With {.columns = pages(x).columns, .rows = 0, .startCol = pages(x).startCol, .startRow = r})
                    Next
    
                    rowSum = DataGridView1.ColumnHeadersHeight + DataGridView1.Rows(r).Height
                    rowCounter = 1
                End If
                If r = DataGridView1.Rows.Count - 2 Then
                    For x As Integer = 0 To maxPagesWide - 1
                        If pages(pageCounter + x).rows = 0 Then
                            pages(pageCounter + x) = New pageDetails With {.columns = pages(pageCounter + x).columns, .rows = rowCounter, .startCol = pages(pageCounter + x).startCol, .startRow = pages(pageCounter + x).startRow}
                        End If
                    Next
                End If
            Next
    
            maxPagesTall = pages.Count \ maxPagesWide
            pagecount = pageCounter
    
            If findingPages Then
                Dim ps As New PrintDialog
                ps.AllowSomePages = True
                ps.PrinterSettings.FromPage = 1
                ps.PrinterSettings.ToPage = pagecount
                If ps.ShowDialog = DialogResult.OK Then
                    If ps.PrinterSettings.PrintRange = PrintRange.SomePages Then
                        ' check FromPage and ToPage are set to appropriate values
                        startPage = ps.PrinterSettings.FromPage
                        endPage = ps.PrinterSettings.ToPage
                    Else
                        startPage = 1
                        endPage = pages.Count
                    End If
                Else
                    e.Cancel = True
                End If
                e.Cancel = True
                findingPages = False
    
            End If
    
    
        End Sub
    
    
        ''' <summary> 
        ''' this is the actual printing routine. 
        ''' using the pagedetails i calculated earlier, it prints a title, 
        ''' + as much of the datagridview as will fit on 1 page, then moves to the next page. 
        ''' this is setup to be dynamic. try resizing the dgv columns or rows 
        ''' </summary> 
        ''' <param name="sender"></param> 
        ''' <param name="e"></param> 
        ''' <remarks></remarks> 
        Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
            'Dim kl As Integer
            
            Dim rect As New Rectangle(20, 20, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Lb1.Height)
            Dim sf As New StringFormat
            sf.Alignment = StringAlignment.Center
            sf.LineAlignment = StringAlignment.Center
    
            If startPage = 1 Then
                e.Graphics.DrawString(Lb1.Text, Lb1.Font, Brushes.Black, rect, sf)
                
                rect = New Rectangle(370, 20, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Label3.Height)
                e.Graphics.DrawString(Label3.Text, Label3.Font, Brushes.Black, rect, sf)
                rect = New Rectangle(450, 10, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Label4.Height)
                e.Graphics.DrawString(Label4.Text, Label4.Font, Brushes.Black, rect, sf)
                rect = New Rectangle(500, 10, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), TextBox2.Height)
                e.Graphics.DrawString(TextBox2.Text, TextBox2.Font, Brushes.Black, rect, sf)
                rect = New Rectangle(490, 40, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), TextBox3.Height)
                e.Graphics.DrawString(TextBox3.Text, TextBox3.Font, Brushes.Black, rect, sf)
                rect = New Rectangle(490, 90, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Label5.Height)
                e.Graphics.DrawString(Label5.Text, Label5.Font, Brushes.Black, rect, sf)
                rect = New Rectangle(310, 20, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Label2.Height)
                e.Graphics.DrawString(Label2.Text, Label2.Font, Brushes.Black, rect, sf)
                rect = New Rectangle(350, 10, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Label1.Height)
                e.Graphics.DrawString(Label1.Text, Label1.Font, Brushes.Black, rect, sf)
    
    
                rect = New Rectangle(250, 2, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), TextBox1.Height)
                e.Graphics.DrawString(TextBox1.Text, TextBox1.Font, Brushes.Black, rect, sf)
    
    
    
    
                'rect = New Rectangle(-310, 50, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Label4.Height)
                'e.Graphics.DrawString(Label4.Text, Label4.Font, Brushes.Black, rect, sf)
                'rect = New Rectangle(-200, 50, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), LbNum.Height)
                'e.Graphics.DrawString(LbNum.Text, LbNum.Font, Brushes.Black, rect, sf)
    
    
    
            End If
            
            sf.Alignment = StringAlignment.Near
            Dim startX As Integer = 50
            Dim startY As Integer = rect.Bottom + 20
            ' Dim rect2 As New Rectangle(20, 20, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Lb1.Height)
            Dim sf2 As New StringFormat
            sf2.Alignment = StringAlignment.Center
            sf2.LineAlignment = StringAlignment.Center
            'If PrintRange.SomePages = True Then
            '    startPage = CInt(System.Drawing.Printing.PrintRange.SomePages.)
            'End If
            Dim pageNumber As Integer
            'If e.PageSettings.PrinterSettings.PrintRange = PrintRange.SomePages Then
            '    '    ' check FromPage and ToPage are set to appropriate values
            '    startPage = e.PageSettings.PrinterSettings.FromPage
            '    '    endPage = e.PageSettings.PrinterSettings.ToPage
            '    'Else
            '    '    startPage = 1
            '    '    endPage = pages.Count
            'End If
            ' printedPageCount = 0
    
            'The 1-based number of the page currently being printed.
    
    
            For p As Integer = startPage - 1 To endPage - 1
                'If startPage = p Then
                'Dim num As Integer
                'num = p + 1
                Label15.Text = "Page N° " & p + 1 & "/" & pages.Count
                Dim rect2 = New Rectangle(690, 1122, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Label15.Height)
                e.Graphics.DrawString(Label15.Text, Label15.Font, Brushes.Black, rect2, sf2)
    
    
    
                'End If
                Dim cell As New Rectangle(startX, startY, DataGridView1.RowHeadersWidth, DataGridView1.ColumnHeadersHeight)
                e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                e.Graphics.DrawRectangle(Pens.Black, cell)
                startY += DataGridView1.ColumnHeadersHeight
                For r As Integer = pages(p).startRow To pages(p).startRow + pages(p).rows - 1
                    cell = New Rectangle(startX, startY, DataGridView1.RowHeadersWidth, DataGridView1.Rows(r).Height)
                    e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                    e.Graphics.DrawRectangle(Pens.Black, cell)
                    e.Graphics.DrawString(DataGridView1.Rows(r).HeaderCell.Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                    startY += DataGridView1.Rows(r).Height
                Next
    
                startX += cell.Width
                startY = rect.Bottom + 20
                For c As Integer = pages(p).startCol To pages(p).startCol + pages(p).columns - 1
                    cell = New Rectangle(startX, startY, DataGridView1.Columns(c).Width, DataGridView1.ColumnHeadersHeight)
                    e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
                    e.Graphics.DrawRectangle(Pens.Black, cell)
                    e.Graphics.DrawString(DataGridView1.Columns(c).HeaderCell.Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                    startX += DataGridView1.Columns(c).Width
                Next
    
                startY = rect.Bottom + DataGridView1.ColumnHeadersHeight + 20
    
                For r As Integer = pages(p).startRow To pages(p).startRow + pages(p).rows - 1
                    startX = 50 + DataGridView1.RowHeadersWidth
                    For c As Integer = pages(p).startCol To pages(p).startCol + pages(p).columns - 1
                        cell = New Rectangle(startX, startY, DataGridView1.Columns(c).Width, DataGridView1.Rows(r).Height)
                        e.Graphics.DrawRectangle(Pens.Black, cell)
                        If DataGridView1.Columns(c).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight Then
                            sf.Alignment = StringAlignment.Near
                        Else
                            sf.Alignment = StringAlignment.Near
                        End If
                        e.Graphics.DrawString(DataGridView1(c, r).Value?.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
                        startX += DataGridView1.Columns(c).Width
                    Next
                    startY += DataGridView1.Rows(r).Height
                Next
    
                If p <> endPage - 1 Then
                    startPage += 1
                    e.HasMorePages = True
                    Return '***ooops - edited here***
                Else
                    startPage = 1
                End If
    
            Next
            'For p As Integer = startPage To pages.Count - 1
            '    'If startPage = p Then
            '    'Dim num As Integer
            '    'num = p + 1
            '    Label15.Text = "Page N° " & p + 1 & "/" & pages.Count
            '    Dim rect2 = New Rectangle(690, 1122, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Label15.Height)
            '    e.Graphics.DrawString(Label15.Text, Label15.Font, Brushes.Black, rect2, sf2)
    
    
    
            '    'End If
            '    Dim cell As New Rectangle(startX, startY, DataGridView1.RowHeadersWidth, DataGridView1.ColumnHeadersHeight)
            '    e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
            '    e.Graphics.DrawRectangle(Pens.Black, cell)
            '    startY += DataGridView1.ColumnHeadersHeight
            '    For r As Integer = pages(p).startRow To pages(p).startRow + pages(p).rows - 1
            '        cell = New Rectangle(startX, startY, DataGridView1.RowHeadersWidth, DataGridView1.Rows(r).Height)
            '        e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
            '        e.Graphics.DrawRectangle(Pens.Black, cell)
            '        e.Graphics.DrawString(DataGridView1.Rows(r).HeaderCell.Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
            '        startY += DataGridView1.Rows(r).Height
            '    Next
    
            '    startX += cell.Width
            '    startY = rect.Bottom + 20
            '    For c As Integer = pages(p).startCol To pages(p).startCol + pages(p).columns - 1
            '        cell = New Rectangle(startX, startY, DataGridView1.Columns(c).Width, DataGridView1.ColumnHeadersHeight)
            '        e.Graphics.FillRectangle(New SolidBrush(SystemColors.ControlLight), cell)
            '        e.Graphics.DrawRectangle(Pens.Black, cell)
            '        e.Graphics.DrawString(DataGridView1.Columns(c).HeaderCell.Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
            '        startX += DataGridView1.Columns(c).Width
            '    Next
    
            '    startY = rect.Bottom + DataGridView1.ColumnHeadersHeight + 20
    
            '    For r As Integer = pages(p).startRow To pages(p).startRow + pages(p).rows - 1
            '        startX = 50 + DataGridView1.RowHeadersWidth
            '        For c As Integer = pages(p).startCol To pages(p).startCol + pages(p).columns - 1
            '            cell = New Rectangle(startX, startY, DataGridView1.Columns(c).Width, DataGridView1.Rows(r).Height)
            '            e.Graphics.DrawRectangle(Pens.Black, cell)
            '            If DataGridView1.Columns(c).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight Then
            '                sf.Alignment = StringAlignment.Near
            '            Else
            '                sf.Alignment = StringAlignment.Near
            '            End If
            '            e.Graphics.DrawString(DataGridView1(c, r).Value.ToString, DataGridView1.Font, Brushes.Black, cell, sf)
            '            startX += DataGridView1.Columns(c).Width
            '        Next
            '        startY += DataGridView1.Rows(r).Height
            '    Next
            '    If p <> pages.Count - 1 Then
            '        startPage = p + 1
            '        e.HasMorePages = True
            '        Return
            '    Else
            '        startPage = 0
            '    End If
            '    'If p = pages.Count - 1 Then
            '    '    ' kl = pages.Count - 1
            '    '    rect = New Rectangle(260, startY, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Label1.Height)
            '    '    e.Graphics.DrawString(Label1.Text, Label1.Font, Brushes.Black, rect, sf2)
            '    '    rect = New Rectangle(500, startY, CInt(PrintDocument1.DefaultPageSettings.PrintableArea.Width), Label14.Height)
            '    '    e.Graphics.DrawString(Label14.Text, Label14.Font, Brushes.Black, rect, sf2)
            '    'End If
            '    'Label15.Text = p
            'Next
    
        End Sub
        'Private ReadOnly items As Integer() = Enumerable.Range(1, 20).ToArray()
        'Private Const itemsPerPage As Integer = 2
        'Private Sub PrintPage(pageNumber As Integer, g As Graphics)
        '    Dim pageData = items.Skip((pageNumber - 1) * itemsPerPage).Take(itemsPerPage)
        '    Dim y = 50
    
        '    For Each item In pageData
        '        g.DrawString(item.ToString(), Font, Brushes.Black, 50, y)
        '        y += 50
        '    Next
        'End Sub
    
        'Private Function HasMorePages(pageNumber As Integer) As Boolean
        '    Dim totalPageCount = CInt(Math.Ceiling(items.Length / itemsPerPage))
    
        '    Return pageNumber < totalPageCount
        'End Function
       Private WithEvents PDB As New ToolStripButton("Choisie une imprimante")
    
        Private Sub PDB_Click1(ByVal sender As Object, ByVal e As EventArgs) Handles PDB.Click
            PrintDialog1.AllowSelection = True
            PrintDialog1.AllowCurrentPage = True
    
            PrintDialog1.AllowSomePages = True
    
            PrintDocument1.PrinterSettings.PrintRange = Drawing.Printing.PrintRange.SomePages
            PrintDocument1.PrinterSettings.FromPage = 2
            PrintDocument1.PrinterSettings.ToPage = 4
    
            If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
    
                PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings
    
                PrintDocument1.Print()
            End If
    
    
    
            Me.Close()
            'Dim ps As New PrintDialog
    
            'If ps.ShowDialog = DialogResult.OK Then
            '    If ps.PrinterSettings.PrintRange = PrintRange.SomePages Then
            '        ' check FromPage and ToPage are set to appropriate values
            '        startPage = ps.PrinterSettings.FromPage
            '        endPage = ps.PrinterSettings.ToPage
            '    Else
            '        startPage = 1
            '        endPage = pages.Count
            '    End If
    
            'End If
            'printedPageCount = 0
    
    
        End Sub
    
        Private Sub PrintedForm_Shown(sender As Object, e As EventArgs) Handles Me.Shown
            Application.DoEvents()
            findingPages = True
            PrintDocument1.Print()
            Dim ppd As New PrintPreviewDialog
            ppd.Document = PrintDocument1
            ppd.ShowDialog()
        End Sub
    End Class

  37. #37
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    25,059

    Re: How to select the page number to print in print preview dialog box?

    Quote Originally Posted by .paul. View Post
    I checked my link. Seems broken. This is the Form I changed...
    You might see some formatting removed as i was restricted in the amount of characters i could post...

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width