0

I have a datagrid of information and when the print button is clicked I want to show a print preview screen of what it will look like and then let the user print the document. Heres what I got so far:

        PrintDocument myDocument = new PrintDocument();


        PrintPreviewDialog PrintPreviewDialog1 = new PrintPreviewDialog();
        PrintPreviewDialog1.Document = myDocument;
        PrintPreviewDialog1.ShowDialog();

My question is how to get the data onto the preview screen.. thanks!

1
  • Are your problems resolved? Commented Feb 12, 2015 at 15:28

1 Answer 1

1

You need to add the PrintPage event:

myDocument.DocumentName = "Test2015";
myDocument.PrintPage += myDocument_PrintPage;

and you need to code it! In its very simplest form this will dump out the data:

void myDocument_PrintPage(object sender, PrintPageEventArgs e)
{
   foreach(DataGridViewRow row in dataGridView1.Rows)
      foreach(DataGridViewCell cell in row.Cells)
      {
          if (Cell.Value != null)
              e.Graphics.DrawString(cell.Value.ToString(), Font,  Brushes.Black, 
                          new Point(cell.ColumnIndex * 123, cell.RowIndex  * 12 ) );
      }
}

But of course you will want to add a lot more to get nice formatting etc..

  • For example you can use the Graphics.MeasureString() method to find out the size of a chunk of text to optimize the coodinates, which are hard coded just for testing here.

  • You may use the cell.FormattedValue instead of the raw Value.

  • You may want to prepare a few Fonts you will use, prefix the dgv with a header, maybe a logo..

Also worth considering is to set the Unit to something device independent like mm:

e.Graphics.PageUnit = GraphicsUnit.Millimeter;

And, if need be, you should keep track of the vertical positions so you can add page numbers and recognize when a Page is full!

Update: Since your DGV may contain empty cells I have added a check for null.

Sign up to request clarification or add additional context in comments.

2 Comments

Will the downvoter care to comment? Thanks for not helping to improve SO!
That is the problem then. I have looked into it; See my answer there!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.