c#虽然有很多数据但没有打印

时间:2014-09-06 11:24:15

标签: c# winforms gridview printing

我有一个网格视图,我想打印它。

这是我的代码:

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) {
            int rowCounter = 0;
            int z = 0;
            StringFormat str = new StringFormat();
            str.Alignment = StringAlignment.Near;
            str.LineAlignment = StringAlignment.Center;
            str.Trimming = StringTrimming.EllipsisCharacter;

            int width = 500 / (GridView.Columns.Count - 2);
            int realwidth = 100;
            int height = 40;

            int realheight = 100;

            for (z = 0; z < GridView.Columns.Count - 1; z++)
            {
                e.Graphics.FillRectangle(Brushes.AliceBlue, realwidth, realheight, width, height);
                e.Graphics.DrawRectangle(Pens.Black, realwidth, realheight, width, height);

                e.Graphics.DrawString(GridView.Columns[z].HeaderText, GridView.Font, Brushes.Black, realwidth, realheight);

                realwidth = realwidth + width;
            }

            z = 0;
            realheight = realheight + height;
            while (rowCounter < GridView.Rows.Count)
            {
                realwidth = 100;
                e.Graphics.FillRectangle(Brushes.AliceBlue, realwidth, realheight, width, height);
                e.Graphics.DrawRectangle(Pens.Black, realwidth, realheight, width, height);

                e.Graphics.DrawString(GridView.Rows[rowCounter].Cells[0].Value.ToString(), GridView.Font, Brushes.Black, realwidth, realheight);
                realwidth = realwidth + width;
            }

            printDialog1.Document = printDocument1;
            printDialog1.ShowDialog();
        }

当用户点击打印按钮时,我这样做:

DialogResult result = printDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                this.printDocument1.Print();
            }

加上表单的构造,我初始化打印变量如下:

this.printDocument1 = new System.Drawing.Printing.PrintDocument();
            this.printDialog1 = new System.Windows.Forms.PrintDialog();

我的问题是,当我点击打印时,虽然网格视图有超过320行,但我得到了空白页

更新1

我正在关注本教程http://code.msdn.microsoft.com/windowsdesktop/CSWinFormPrintDataGridView-75864c45

更新2

网格视图变量为GridView

我猜这段代码很简单

更新3

我添加了

++rowCounter;
realheight = realheight + height;

广告while循环的结尾,结果仍然相同

1 个答案:

答案 0 :(得分:1)

您发布的代码至少有三个问题:

  • 在你的行循环中,你不会推进行计数器,这将导致无限循环。
  • 您也不会推进您的实际高度变量,这会导致所有行的叠印
  • 因为没有发生这种情况所以你的printDocument1_PrintPage事件没有被调用;您可能只复制了示例中的代码,而实际上并没有将它与printDocument1连接起来。

添加到循环结束:

rowCounter++;
realheight += height;

并在构造函数中:

this.printDocument1.PrintPage += this.printDocument1_PrintPage;

解决这些问题至少应该打印出来......