when i print the items in my listboxes it just keeps going and when it gets to the end of the page, it justs cuts off the rest. how do i get it to go to the next page. This is the code i have

private void docPrint_PrintPage(object sender, PrintPageEventArgs e)
         {
             float linesPerPage = 0;
             float yPos = 0;
             float xPos = 0;
             int count = 0;
             float leftMargin = e.MarginBounds.Left;
             float topMargin = e.MarginBounds.Top;
             string line = null;
             string line2 = null;
             m_objFont = new Font("Arial", 12);


             // Calculate the number of lines per page.
             linesPerPage = e.MarginBounds.Height /
             m_objFont.GetHeight(e.Graphics);

             // Print each line of the file.
             foreach (Control objControl in this.Controls)
             {
                 if (objControl.GetType().Name != "Button" && objControl.GetType().Name != "MenuStrip" && objControl.Name != "lblItemName" && objControl.Name != "lblItemValue" )
                 {
                     line = objControl.Text;

                     switch (objControl.Name)
                     {
                         case "lblSum":
                             e.Graphics.DrawRectangle(Pens.Black, lblSum.Location.X + leftMargin, lblSum.Location.Y + topMargin - 4, lblSum.Width, lblSum.Height);
                             m_objFont = objControl.Font;
                             break;

                         default:
                             m_objFont = objControl.Font;
                             m_objFont = new Font("Arial", 12);
                             break;

                     }
                     xPos = leftMargin + objControl.Location.X;
                     yPos = topMargin + objControl.Location.Y;
                    
                     e.Graphics.DrawString(line, m_objFont, Brushes.Black, xPos, yPos);
                 }
             }

             

             while (count < linesPerPage && nextItem < lstResult.Items.Count && nextItem < lstResult.Items.Count)
             {
                 m_objFont = new Font("Arial", 12, FontStyle.Underline);
                 yPos = topMargin + 210 + (count *
                 m_objFont.GetHeight(e.Graphics));
                 line = lstResult.Items[nextItem].ToString();
                 line2 = lstResult2.Items[nextItem].ToString();

                 e.Graphics.DrawString(line, m_objFont, Brushes.Black,
                 leftMargin, yPos, new StringFormat());
                 
                 e.Graphics.DrawString(line2, m_objFont, Brushes.Black, leftMargin + 500, yPos, new StringFormat());
                 count++;
                 nextItem++;
             }
                    
                     // If more lines exist, print another page.
                     if (nextItem < lstResult.Items.Count - 1 && nextItem < lstResult2.Items.Count - 1)
                         e.HasMorePages = true;
                     else
                     {
                         e.HasMorePages = false;
                         nextItem = 0;
                     }
                 }
         
         
     

                         
                     
                 



             
             
         
         private void mnuFilePrint_Click(object sender, EventArgs e)
         {
             PrintDocument docPrint = new PrintDocument();
             docPrint.PrintPage += new PrintPageEventHandler(docPrint_PrintPage);

             if (PrinterSettings.InstalledPrinters.Count == 0)
             {
                 ErrorMessage();
                 return;
             }
             docPrint.Print();
         }

         private void mnuFilePrintPreview_Click(object sender, EventArgs e)
         {
             PrintDocument docPrint = new PrintDocument();

             docPrint.PrintPage += new PrintPageEventHandler(docPrint_PrintPage);
             if (PrinterSettings.InstalledPrinters.Count == 0)
             {
                 ErrorMessage();
                 return;
             }
             objPreview.Document = docPrint;
             objPreview.ShowDialog();
         }
         void ErrorMessage()
         {
             MessageBox.Show("No printers istalled. You must" + "have a printer installed to preview or print" + "the document.", "Print Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
        

       

       
     
       
    }
}

Dani AI

Generated

A few concrete points that explain why the print job either stops at the page bottom or runs forever, and how to fix both problems without rewriting the whole routine.

The core rules

  • Keep a single, class-level index (the thread calls it nextItem) that is initialized to 0 when a print or preview job starts and is NOT reset on every PrintPage call. Reset that index only when the whole print job is finished (or right before starting a new one). This is the key point from .
  • Compute how many lines fit on a page from the printable area minus any header/footer space, and force a minimum of one line per page. If that calculation returns 0 or negative, the page loop never advances the index and setting HasMorePages = true creates an infinite loop.
  • Use simple bounds checks (no “-1” tricks). After drawing the page, set HasMorePages to whether the index is still less than the total items remaining.

Minimal pattern (illustrative)

// class-level:
int currentIndex = 0;

// at start of printing/preview:
currentIndex = 0;

// inside PrintPage:
float headerHeight = 200f; // height reserved for controls/header
float lineHeight = font.GetHeight(e.Graphics);
int linesPerPage = Math.Max(1, (int)((e.MarginBounds.Height - headerHeight) / lineHeight));

int count = 0;
while (count < linesPerPage && currentIndex < totalItems)
{
  float y = e.MarginBounds.Top + headerHeight + count * lineHeight;
  e.Graphics.DrawString(items[currentIndex], font, Brushes.Black, e.MarginBounds.Left, y);
  count++; currentIndex++;
}

e.HasMorePages = (currentIndex < totalItems);
if (!e.HasMorePages) currentIndex = 0;

Extra tips tied to this thread

  • If printing two listboxes side-by-side, check bounds for each list before reading its item (or use the smaller count as the loop limit). The original code had a duplicated check and mismatched bounds that can cause index errors.
  • For controls printed once (headers), either draw them only on the first page (track a page counter) or reserve headerHeight so the list area doesn’t overlap them.
  • When debugging paging issues, log linesPerPage and the index before/after the page routine; that will quickly reveal a zero linesPerPage or an index that never advances.

This addresses both the “does not go to the next page” and the “infinite pages” behaviours seen in the thread: incorrect index handling, off-by-one checks, and an invalid linesPerPage computation.

Recommended Answers

All 11 Replies

I looked at the tutorial but i still dont know why it doesnt go to the next page. my code is in the first post

any help would be appreciated

i looked at that thread that you posted but its still unclear to me whats wrong with my code.

Then you shold give a clear explanation of what exactly is still unclair to you.

in the if/else statement

//If more lines exist, print another page.                    
 if (nextItem < lstResult.Items.Count - 1 && nextItem < lstResult2.Items.Count - 1) 
    e.HasMorePages = true;       
 else                    
 {                        
   e.HasMorePages = false;                    
     nextItem = 0;     
 }

when i use this i dont get the next page. when i used what it said in the other thread, i get an infinate number of pages. i dont know what to put to make it so that it doesnt go on for an infinate number of pages.

lstResult and lstResult2 are listboxes btw

i tried changing the code to what was on the other thread but it just results in an infinate number of pages

does anyone know whats wrong with this code? i dont want it to run on endlessly without going to the next page.

1. Do not reset nextItem variable.

2. Want set top margin then set height of document.

float topMargin = e.MarginBounds.Top + 200;

linesPerPage = (e.MarginBounds.Height - 200) / m_objFont.GetHeight(e.Graphics);

 while (count < linesPerPage && linesprinted < totallines)
          {
         yPos = topMargin  + (count * m_objFont.GetHeight(e.Graphics));
         ....
          }

Have a look at sample app.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
namespace printmulti
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Adding 200 lines of text into listbox.
            for (int i = 1; i <= 200; i++)
            {
                listBox1.Items.Add("Item #" + i);
            }
        }


        Font m_objFont;
        int totallines = 0;    //Total lines to be print
        int linesprinted = 0;  //printed lines count

        //Print - Button
        private void button1_Click(object sender, EventArgs e)
        {
            PrintDocument pd = new PrintDocument();
            totallines = listBox1.Items.Count;
            linesprinted = 0;
            m_objFont = new Font("Arial", 12);

            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            pd.Print();
        }

        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float linesPerPage = 0;
            float yPos = 0;
            int count = 0;
            string line = "";

            float leftMargin = e.MarginBounds.Left;
            float topMargin = e.MarginBounds.Top + 200;


            linesPerPage = (e.MarginBounds.Height - 200) / m_objFont.GetHeight(e.Graphics);


            while (count < linesPerPage && linesprinted < totallines)
            {
                yPos = topMargin + (count * m_objFont.GetHeight(e.Graphics));

                line = listBox1.Items[linesprinted].ToString();

                e.Graphics.DrawString(line, m_objFont, Brushes.Black,
                leftMargin, yPos, new StringFormat());

                count++;
                linesprinted++;
            }

            if (linesprinted < totallines)
                e.HasMorePages = true;
            else
                e.HasMorePages = false;

        }

        //Preview - Button
        private void button2_Click(object sender, EventArgs e)
        {
            PrintDocument pd = new PrintDocument();
            totallines = listBox1.Items.Count;
            linesprinted = 0;
            m_objFont = new Font("Arial", 12);
            PrintPreviewDialog preview = new PrintPreviewDialog();


            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            preview.Document = pd;
            preview.ShowDialog();
        }
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.