1

我正在尝试打印 DataGridView 并且打印机只打印白页。我知道 datagridview 不是空的,因为它出现在表单上。我也试过用 PrintPreviewDialog 来做,但它也显示了一个白页。代码是这样的,我不知道出了什么问题。

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;
                }
            }
    }
}
4

1 回答 1

2

您忘记为打印过程添加 EventHandler。

private void imprimirBtn_Click(object sender, EventArgs e)
    {   
        printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
        printDocument1.Print();
    }
于 2014-04-15T10:46:58.503 回答