在 C# 中打印数据网格视图

本文关键字:数据网 网格 视图 数据 打印 | 更新日期: 2023-09-27 18:34:12

我正在处理一个项目,在这里我需要用打印机打印数据网格视图。我使用了以下代码。

 private void printToolStripMenuItem_Click(object sender, EventArgs e)
    {
        try
        {
            PrintDocument pd = new PrintDocument();
            pd.DefaultPageSettings.PaperSize = new PaperSize("A4", 827, 1170); // all sizes are converted from mm to inches & then multiplied by 100.
            pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
            //pd.PrinterSettings = PrinterSettings.InstalledPrinters.
            pd.Print();
        }
        catch (Exception ex)
        {
            MessageBox.Show("An error occurred while printing", ex.ToString());
        }
    }
    private void pd_PrintPage(object sender, PrintPageEventArgs ev)
    {
        if (t < 1)
        {
            ev.Graphics.DrawString("Hello YouTube", new Font("Times New Roman", 14, FontStyle.Bold), Brushes.Black, 20, 225);
            t++;
            if (t < 1)
            {
                ev.HasMorePages = true;
            }
            else
            {
                ev.HasMorePages = false;
            }
        }
    }

现在,此代码打印可以打印hello youtube或我们在该字符串中给出的任何内容。但是我们需要打印一个数据网格视图而不是它。那么,我们应该更改代码的哪一部分呢?

在 C# 中打印数据网格视图

我认为这就是你要找的,否则点击这里

private void printToolStripMenuItem_Click(object sender, EventArgs e)
    {
        try
        {
            PrintDocument pd = new PrintDocument();
            pd.DefaultPageSettings.PaperSize = new PaperSize("A4", 827, 1170); // all sizes are converted from mm to inches & then multiplied by 100.
            pd.PrintPage += printDocument_PrintPage; //event handler fire
            //pd.PrinterSettings = PrinterSettings.InstalledPrinters.
            pd.Print();
        }
        catch (Exception ex)
        {
            MessageBox.Show("An error occurred while printing", ex.ToString());
        }
    }

 private void printDocument_PrintPage(object sender, PrintPageEventArgs ev)
    {
        Graphics graphic = ev.Graphics;
        foreach (DataRow row in dataGridView1.Rows)
            {
                string text = row.ToString() //or whatever you want from the current row
                graphic.DrawString(text,new Font("Times New Roman", 14, FontStyle.Bold), Brushes.Black, 20, 225);
            }
    }

用于循环循环遍历 DataGridView 内容,而不是 helloyoutube,指定必须分发其内容的列

 for(int i=0;i<dg.rows.count;i++)
 {
  ev.Graphics.DrawString(dg.rows[i].cells["columnname"].value, new Font("Times New Roman",               14, FontStyle.Bold), Brushes.Black, 20, 225);
 }