c# - 打印多个 datagridview 页面

标签 c# datagridview

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

这是我当前的代码:

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 循环将不起作用,因为您告诉打印机打印当前页面上的所有内容。

您必须在 PrintPage 方法范围之外有一个变量来跟踪您当前所在的行索引:

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 值:

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

如果您添加另一个变量,例如 int printPage;,您现在也可以通过在 PrintPage 事件中递增该值来了解当前正在打印哪一页。

关于c# - 打印多个 datagridview 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24079360/

相关文章:

C# 获取 Firefox 中所有打开页面的 URL

c# - 将 DataGridView 图像单元格与文本单元格合并

c# - 使用光标键在 DataGridView 中的 DataGridViewCell 内部移动

c# - 过滤数据表数字列

c# - dataGridView1.Columns.Clear() 抛出 IndexOutOfRange 异常

c# - 如何发送 HL7 ACK 消息作为 TCP 响应?

c# - 轻量级消息库?

c# - 存储股票报价(财务)数据的最佳方法

c# - MongoDB C# 实体映射 : "one to many relation"

c# - 如何将DataGridView动态添加到TabPage