Click here to Skip to main content
15,879,095 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a bug in print preview this is my PrintDocument code:
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
            float linesPerPage = 0;
            float yPosition = 0;
            int count = 0;
            float leftMargin = e.MarginBounds.Left;
            float topMargin = e.MarginBounds.Top;
            string line = null;
            Font printFont = this.rtbWord.Font;
            SolidBrush myBrush = new SolidBrush(Color.Black);
            linesPerPage = e.MarginBounds.Height / printFont.GetHeight(e.Graphics);

            while (count < linesPerPage && ((line = myReader.ReadLine()) != null))
                yPosition = topMargin + (count * printFont.GetHeight(e.Graphics));
                // draw the next line in the rich edit control
                e.Graphics.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());
            // If there are more lines, print another page.
            if (line != null)
                e.HasMorePages = true;
                e.HasMorePages = false;

and this is my PrintPreview code:
private void printPreView_Click(object sender, EventArgs e)
            PrintPreviewDialog PrintPreviewDialog = new PrintPreviewDialog();
            PrintPreviewDialog.Document = printDocument1;
            if (PrintPreviewDialog.ShowDialog() == DialogResult.OK)

in the line
while (count < linesPerPage && ((line = myReader.ReadLine()) != null))

i have this error:
Object reference not set to an instance of an object.

plz help me.

1 solution

Since you don't show us more of your code, my guess is, that you did not instantiate the instance of myReader as in this sample:
private StringReader myReader;
public Form1()
   string line = myReader.ReadLine(); //throws: Object reference not set to an instance of an object.

To solve that issue you need to create the StringReader object as in this sample, but you need to fill it with your content.
private StringReader myReader;
public Form1()
   myReader = new StringReader("HelloWorld");
   string line = myReader.ReadLine();
Share this answer
amirmohamad 1-Oct-12 1:15am    
this is myReader
private StringReader myReader;
JF2015 1-Oct-12 1:19am    
The solution is the same. You need to instantiate the StringReader object before you can use it - just fill it with your content. In my sample I just filled it with "HelloWorld", but you have your own content in there - probably the text you want to print.
amirmohamad 1-Oct-12 1:28am    
you are good man tank's for help.
vote 5+

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900