Eri-Ka
Eri-Ka

Reputation: 49

C# PrintDocument only prints an empty page

I´m trying to print a DataGridView and the printer only prints an white page. I know that the datagridview is not empty because it appear on the form. I tried also doing it with PrintPreviewDialog but its shows also a white page. The code is this and I dont know what is wrong.

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 Prueba
{
    public partial class Form4 : Form
    {
        public Form4()
        {
            InitializeComponent();
        }
        private void imprimirBtn_Click(object sender, EventArgs e)
        {   
            printDocument1.Print();
        }
        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            Font printFont = new Font("Arial", 10);
            float topMargin = e.MarginBounds.Top;
            float yPos = 0;
            float linesPerPage = 0;
            int count = 0;
            string texto = "";
            int i = -1;
            DataGridViewRow row;

            linesPerPage = e.MarginBounds.Height / printFont.GetHeight(e.Graphics);

            while (count < linesPerPage && i < this.dataGridView1.Rows.Count)
            {
                row = dataGridView1.Rows[i];
                texto = "";

                foreach (DataGridViewCell celda in row.Cells)
                {
                    texto += "\t" + celda.Value.ToString();
                }
                yPos = topMargin + (count * printFont.GetHeight(e.Graphics));
                e.Graphics.DrawString(texto, printFont, Brushes.Black, 10, yPos);

                count++;
                i++;
                if (i < this.dataGridView1.Rows.Count)
                    e.HasMorePages = true;
                else
                {
                    i = 0;
                }
            }
    }
}

Upvotes: 1

Views: 4007

Answers (1)

rguarascia.ts
rguarascia.ts

Reputation: 813

You forgot to add the EventHandler for the printing process.

private void imprimirBtn_Click(object sender, EventArgs e)
    {   
        printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
        printDocument1.Print();
    }

Upvotes: 2

Related Questions