打印多个datagridview页面 [英] Print multiple datagridview pages

查看:57
本文介绍了打印多个datagridview页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印我的 DataGridView 内容,但是当我在 DataGridView 中有很多行时,不知道我如何使用 HasMorePages 属性。

I'd like to print my DataGridView content, but when I have many rows in this DataGridView I don't know how need I use the HasMorePages property.

这是我当前的代码:

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    foreach (DataGridViewRow sor in dataGridView1.Rows)
    {
        foreach (DataGridViewColumn oszlop in dataGridView1.Columns)
        {
            szelesseg += oszlop.Width;

            e.Graphics.DrawRectangle(Pens.Brown, szelesseg, magassag, oszlop.Width, sor.Height);

            szelesseg_lista.Add(szelesseg);
            magassag_lista.Add(magassag);
        }

        foreach (DataGridViewCell cella in sor.Cells)
        {
            ertekek.Add(cella.Value.ToString());
        }

        szelesseg = 10;
        magassag = magassag + sor.Height;

        cella_magassag += sor.Height;

    }


    int sor_db = ertekek.Count;

    for (int i = 0; i < sor_db; i++)
    {
        e.Graphics.DrawString(ertekek[i], new Font(FontFamily.GenericMonospace, 12, FontStyle.Regular), new SolidBrush(Color.Red), szelesseg_lista[i], magassag_lista[i]);

    }
}


推荐答案

PrintPage事件适用于您要打印的每个页面。这意味着您的For ... Each循环将无法工作,因为您要告诉打印机在当前页面上打印所有内容。

The PrintPage event is for every page you want to print. That means your For...Each loop won't work since you are telling the printer to print everything on the current page.

您必须在PrintPage方法范围可跟踪您当前所在的行索引:

You have to have a variable outside the PrintPage method scope to keep track of which row index you are currently on:

int printIndex;

private void printDocument1_PrintPage(object sender, PrintPageEventArgs e) {

  int y = 0;

  while (printIndex < dataGridView1.Rows.Count && 
         y + dataGridView1.Rows[printIndex].Height < e.MarginBounds.Height) {

    // print your stuff, y is where you are on the page vertically

    y += dataGridView1.Rows[printIndex].Height;
    ++printIndex;
  }

  e.HasMorePages = printIndex < dataGridView1.Rows.Count;
}

使用BeginPrint事件重置您的printIndex值:

Use the BeginPrint event to reset your printIndex value:

private void printDocument1_BeginPrint(object sender, PrintEventArgs e) {
  printIndex = 0;
}

如果添加其他变量,例如 int printPage ; ,现在您还可以通过在PrintPage事件中增加该值来知道当前正在打印的页面。

If you add another variable, such as int printPage;, you can now know which page you are currently printing, too, by incrementing that value in the PrintPage event.

这篇关于打印多个datagridview页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆