我正在尝试打印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;
}
}
}
}
答案 0 :(得分:1)
您忘记为打印过程添加EventHandler。
private void imprimirBtn_Click(object sender, EventArgs e)
{
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
printDocument1.Print();
}