如何从一个DataGridView控制打印值 [英] How to print values from a DataGridView control

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

问题描述

我有,有一个 DataGridView的控制的应用程序,它认为我想打印出来的时候,打印按钮被按下的数据。

到目前为止,我已经拿到了打印按钮的工作,但是当我的应用程序打印的页面出来空白!

如何修改我的code,使要打印的数据?

 公共部分类frmViewBook​​ings:表单
{
    私人无效btnClose_Click(对象发件人,EventArgs的发送)
    {
        Form3炫魅=新Form3();
        mainpage.Show();
        this.Close();
    }    私人无效frmViewBook​​ings_Load(对象发件人,EventArgs的发送)
    {
        this.bookingTableAdapter.Fill(this.usersDataSet1.Booking);
    }    私人无效printDocument1_PrintPage(对象发件人,PrintPageEventArgs E)
    {
        VAR myPaintArgs =新PaintEventArgs的
        (
            e.Graphics,
            新的Rectangle(新点(0,0),this.Size)
        );        this.InvokePaint(dataGridView1,myPaintArgs);
    }    私人无效btnPrint_Click(对象发件人,EventArgs的发送)
    {
        printDocument1.Print();
    }
}


解决方案

我previously测试这个类的打印数据网格视图内容

这个类添加到您的项目:

 类ClsPrint
    {
        #区域变量        INT iCellHeight = 0; //用于获取/设置datagridview的单元格高度
        INT iTotalWidth = 0; //
        INT iRow = 0; //用作反
        布尔bFirstPage = FALSE; //用于检查我们是否打印第一页
        布尔bNewPage = FALSE; //用于检查我们是否打印了新的一页
        INT iHeaderHeight = 0; //用于表头的高度
        的StringFormat strFormat; //用于格式化网格行。
        ArrayList的arrColumnLefts =新的ArrayList(); //用于保存列的左坐标
        ArrayList的arrColumnWidths =新的ArrayList(); //用于保存列宽
        私人的PrintDocument _printDocument =新的PrintDocument();
        私人的DataGridView GW =新的DataGridView();
        私人字符串_ReportHeader;        #endregion        公共ClsPrint(DataGridView的GridView控件,串ReportHeader)
        {
            _printDocument.PrintPage + =新PrintPageEventHandler(_printDocument_PrintPage);
            _printDocument.BeginPrint + =新PrintEventHandler(_printDocument_BeginPrint);
            GW = gridview的;
            _ReportHeader = ReportHeader;
        }        公共无效PrintForm-IS成形()
        {
            ////打开打印对话框
            // PrintDialog类PrintDialog类=新PrintDialog类();
            //printDialog.Document = _printDocument;
            //printDialog.UseEXDialog = TRUE;            ////获取文档
            //如果(DialogResult.OK == printDialog.ShowDialog())
            // {
            // _printDocument.DocumentName =测试页打印;
            // _printDocument.Print();
            //}            //打开打印preVIEW对话框
            打印previewDialog objPPdialog =新打印previewDialog();
            objPPdialog.Document = _printDocument;
            objPPdialog.ShowDialog();
        }        私人无效_printDocument_PrintPage(对象发件人,System.Drawing.Printing.PrintPageEventArgs E)
        {
            //尝试
            // {
            //设置左旁
            INT iLeftMargin = e.MarginBounds.Left;
            //设置上边距
            INT iTopMargin = e.MarginBounds.Top;
            //是否有更多的页面必须打印或不
            布尔bMorePagesToPrint = FALSE;
            INT iTmpWidth = 0;            //为第一页打印设置单元格的宽度和高度的头
            如果(bFirstPage)
            {
                的foreach(的DataGridViewColumn GridCol在gw.Columns)
                {
                    iTmpWidth =(INT)(Math.Floor((双)((双)GridCol.Width /
                        (双)iTotalWidth *(双)iTotalWidth *
                        ((双)e.MarginBounds.Width /(双)iTotalWidth))));                    iHeaderHeight =(INT)(e.Graphics.MeasureString(GridCol.HeaderText,
                        GridCol.InheritedStyle.Font,iTmpWidth).Height)+ 11;                    //保存宽度和头部的高度
                    arrColumnLefts.Add(iLeftMargin);
                    arrColumnWidths.Add(iTmpWidth);
                    iLeftMargin + = iTmpWidth;
                }
            }
            //循环直到没有得到打印所有网格行
            而(iRow< = gw.Rows.Count - 1)
            {
                一个DataGridViewRow GridRow = gw.Rows [iRow]
                //设置单元格高度
                iCellHeight = GridRow.Height + 5;
                INT ICOUNT = 0;
                //检查当前页面设置是否允许更多的行打印
                如果(iTopMargin + iCellHeight> = e.MarginBounds.Height + e.MarginBounds.Top)
                {
                    bNewPage = TRUE;
                    bFirstPage = FALSE;
                    bMorePagesToPrint =真;
                    打破;
                }
                其他
                {                    如果(bNewPage)
                    {
                        //绘制标题
                        e.Graphics.DrawString(_ReportHeader,
                            新字体(gw.Font,FontStyle.Bold)
                            Brushes.Black,e.MarginBounds.Left,
                            e.MarginBounds.Top - e.Graphics.MeasureString(_ReportHeader,
                            新字体(gw.Font,FontStyle.Bold)
                            e.MarginBounds.Width).Height - 13);                        串strDate =;
                        //绘制日期
                        e.Graphics.DrawString(strDate,
                            新字体(gw.Font,FontStyle.Bold),Brushes.Black,
                            e.MarginBounds.Left +
                            (e.MarginBounds.Width - e.Graphics.MeasureString(strDate,
                            新字体(gw.Font,FontStyle.Bold)
                            e.MarginBounds.Width).WIDTH)
                            e.MarginBounds.Top - e.Graphics.MeasureString(_ReportHeader,
                            新字体(新字体(gw.Font,FontStyle.Bold)
                            FontStyle.Bold),e.MarginBounds.Width).Height - 13);                        //绘制列
                        iTopMargin = e.MarginBounds.Top;
                        的DataGridViewColumn [] = _GridCol新的DataGridViewColumn [gw.Columns.Count]
                        INT colcount = 0;
                        //转换LTR到RTL
                        的foreach(的DataGridViewColumn GridCol在gw.Columns)
                        {
                            _GridCol [colcount ++] = GridCol;
                        }
                        的for(int i =(_GridCol.Count() - 1); I> = 0;我 - )
                        {
                            e.Graphics.FillRectangle(新SolidBrush(Color.LightGray)
                                新的Rectangle((int)的arrColumnLefts [ICOUNT],iTopMargin,
                                (INT)arrColumnWidths [ICOUNT],iHeaderHeight));                            e.Graphics.DrawRectangle(Pens.Black,
                                新的Rectangle((int)的arrColumnLefts [ICOUNT],iTopMargin,
                                (INT)arrColumnWidths [ICOUNT],iHeaderHeight));                            e.Graphics.DrawString(_GridCol [I] .HeaderText,
                                _GridCol [I] .InheritedStyle.Font,
                                新SolidBrush(_GridCol [I] .InheritedStyle.ForeColor)
                                新的RectangleF((int)的arrColumnLefts [ICOUNT],iTopMargin,
                                (INT)arrColumnWidths [ICOUNT],iHeaderHeight),strFormat);
                            ICOUNT ++;
                        }
                        bNewPage = FALSE;
                        iTopMargin + = iHeaderHeight;
                    }
                    ICOUNT = 0;
                    DataGridViewCell的[] _GridCell =新的DataGridViewCell [GridRow.Cells.Count]
                    INT cellcount = 0;
                    //转换LTR到RTL
                    的foreach(DataGridViewCell的切尔在GridRow.Cells)
                    {
                        _GridCell [cellcount ++] =切尔;
                    }
                    //绘制列目录
                    的for(int i =(_GridCell.Count() - 1); I> = 0;我 - )
                    {
                        如果(_GridCell [I] .value的!= NULL)
                        {
                            e.Graphics.DrawString(_GridCell [I] .FormattedValue.ToString()
                                _GridCell [I] .InheritedStyle.Font,
                                新SolidBrush(_GridCell [I] .InheritedStyle.ForeColor)
                                新的RectangleF((int)的arrColumnLefts [ICOUNT]
                                (浮点)iTopMargin,
                                (INT)arrColumnWidths [ICOUNT](浮点)iCellHeight)
                                strFormat);
                        }
                        //绘制细胞国界
                        e.Graphics.DrawRectangle(Pens.Black,
                            新的Rectangle((int)的arrColumnLefts [ICOUNT],iTopMargin,
                            (INT)arrColumnWidths [ICOUNT],iCellHeight));
                        ICOUNT ++;
                    }
                }
                iRow ++;
                iTopMargin + = iCellHeight;
            }
            //如果有更多的行,打印另一页。
            如果(bMorePagesToPrint)
                e.HasMorePages = TRUE;
            其他
                e.HasMorePages = FALSE;
            //}
            //赶上(例外EXC)
            // {
            // MessageBox.Show(exc.Message,错误,MessageBoxButtons.OK,
            // MessageBoxIcon.Error);
            //}
        }        私人无效_printDocument_BeginPrint(对象发件人,System.Drawing.Printing.PrintEventArgs E)
        {
            尝试
            {
                strFormat =新的StringFormat();
                strFormat.Alignment = StringAlignment.Center;
                strFormat.LineAlignment = StringAlignment.Center;
                strFormat.Trimming = StringTrimming.EllipsisCharacter;                arrColumnLefts.Clear();
                arrColumnWidths.Clear();
                iCellHeight = 0;
                iRow = 0;
                bFirstPage = TRUE;
                bNewPage = TRUE;                //计算总宽度
                iTotalWidth = 0;
                的foreach(的DataGridViewColumn dgvGridCol在gw.Columns)
                {
                    iTotalWidth + = dgvGridCol.Width;
                }
            }
            赶上(异常前)
            {
                MessageBox.Show(ex.Message,错误,MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
        }    }

对于使用:这将显示与网格视图结果打印对话框

  ClsPrint _ClsPrint =新ClsPrint(dataGridView1,头文字DOC);
 _ClsPrint.PrintForm();

结果

进一步的信息和完整的例子proejct

I have an application that has a DataGridView control, which holds data that I want to print out when the "print" button is pushed.

So far I have got the "print" button working, but when I print on the application the page comes out blank!

How do I edit my code to enable the data to be printed?

public partial class frmViewBookings : Form
{
    private void btnClose_Click(object sender, EventArgs e)
    {
        Form3 mainpage = new Form3();
        mainpage.Show();
        this.Close();
    }

    private void frmViewBookings_Load(object sender, EventArgs e)
    {
        this.bookingTableAdapter.Fill(this.usersDataSet1.Booking);
    }

    private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
    {
        var myPaintArgs = new PaintEventArgs
        (
            e.Graphics,
            new Rectangle(new Point(0, 0), this.Size)
        );

        this.InvokePaint(dataGridView1, myPaintArgs);
    } 

    private void btnPrint_Click(object sender, EventArgs e)
    {
        printDocument1.Print();
    }
}

解决方案

I previously Test this class for Print data grid view content

Add this class to your project:

  class ClsPrint
    {
        #region Variables

        int iCellHeight = 0; //Used to get/set the datagridview cell height
        int iTotalWidth = 0; //
        int iRow = 0;//Used as counter
        bool bFirstPage = false; //Used to check whether we are printing first page
        bool bNewPage = false;// Used to check whether we are printing a new page
        int iHeaderHeight = 0; //Used for the header height
        StringFormat strFormat; //Used to format the grid rows.
        ArrayList arrColumnLefts = new ArrayList();//Used to save left coordinates of columns
        ArrayList arrColumnWidths = new ArrayList();//Used to save column widths
        private PrintDocument _printDocument = new PrintDocument();
        private DataGridView gw = new DataGridView();
        private string _ReportHeader;

        #endregion

        public ClsPrint(DataGridView gridview, string ReportHeader)
        {
            _printDocument.PrintPage += new PrintPageEventHandler(_printDocument_PrintPage);
            _printDocument.BeginPrint += new PrintEventHandler(_printDocument_BeginPrint);
            gw = gridview;
            _ReportHeader = ReportHeader;
        }

        public void PrintForm()
        {
            ////Open the print dialog
            //PrintDialog printDialog = new PrintDialog();
            //printDialog.Document = _printDocument;
            //printDialog.UseEXDialog = true;

            ////Get the document
            //if (DialogResult.OK == printDialog.ShowDialog())
            //{
            //    _printDocument.DocumentName = "Test Page Print";
            //    _printDocument.Print();
            //}

            //Open the print preview dialog
            PrintPreviewDialog objPPdialog = new PrintPreviewDialog();
            objPPdialog.Document = _printDocument;
            objPPdialog.ShowDialog();
        }

        private void _printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            //try
            //{
            //Set the left margin
            int iLeftMargin = e.MarginBounds.Left;
            //Set the top margin
            int iTopMargin = e.MarginBounds.Top;
            //Whether more pages have to print or not
            bool bMorePagesToPrint = false;
            int iTmpWidth = 0;

            //For the first page to print set the cell width and header height
            if (bFirstPage)
            {
                foreach (DataGridViewColumn GridCol in gw.Columns)
                {
                    iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
                        (double)iTotalWidth * (double)iTotalWidth *
                        ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                    iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
                        GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;

                    // Save width and height of headers
                    arrColumnLefts.Add(iLeftMargin);
                    arrColumnWidths.Add(iTmpWidth);
                    iLeftMargin += iTmpWidth;
                }
            }
            //Loop till all the grid rows not get printed
            while (iRow <= gw.Rows.Count - 1)
            {
                DataGridViewRow GridRow = gw.Rows[iRow];
                //Set the cell height
                iCellHeight = GridRow.Height + 5;
                int iCount = 0;
                //Check whether the current page settings allows more rows to print
                if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
                {
                    bNewPage = true;
                    bFirstPage = false;
                    bMorePagesToPrint = true;
                    break;
                }
                else
                {

                    if (bNewPage)
                    {
                        //Draw Header
                        e.Graphics.DrawString(_ReportHeader,
                            new Font(gw.Font, FontStyle.Bold),
                            Brushes.Black, e.MarginBounds.Left,
                            e.MarginBounds.Top - e.Graphics.MeasureString(_ReportHeader,
                            new Font(gw.Font, FontStyle.Bold),
                            e.MarginBounds.Width).Height - 13);

                        String strDate = "";
                        //Draw Date
                        e.Graphics.DrawString(strDate,
                            new Font(gw.Font, FontStyle.Bold), Brushes.Black,
                            e.MarginBounds.Left +
                            (e.MarginBounds.Width - e.Graphics.MeasureString(strDate,
                            new Font(gw.Font, FontStyle.Bold),
                            e.MarginBounds.Width).Width),
                            e.MarginBounds.Top - e.Graphics.MeasureString(_ReportHeader,
                            new Font(new Font(gw.Font, FontStyle.Bold),
                            FontStyle.Bold), e.MarginBounds.Width).Height - 13);

                        //Draw Columns                 
                        iTopMargin = e.MarginBounds.Top;
                        DataGridViewColumn[] _GridCol = new DataGridViewColumn[gw.Columns.Count];
                        int colcount = 0;
                        //Convert ltr to rtl
                        foreach (DataGridViewColumn GridCol in gw.Columns)
                        {
                            _GridCol[colcount++] = GridCol;
                        }
                        for (int i = (_GridCol.Count() - 1); i >= 0; i--)
                        {
                            e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                                new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                (int)arrColumnWidths[iCount], iHeaderHeight));

                            e.Graphics.DrawRectangle(Pens.Black,
                                new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                                (int)arrColumnWidths[iCount], iHeaderHeight));

                            e.Graphics.DrawString(_GridCol[i].HeaderText,
                                _GridCol[i].InheritedStyle.Font,
                                new SolidBrush(_GridCol[i].InheritedStyle.ForeColor),
                                new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                                (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                            iCount++;
                        }
                        bNewPage = false;
                        iTopMargin += iHeaderHeight;
                    }
                    iCount = 0;
                    DataGridViewCell[] _GridCell = new DataGridViewCell[GridRow.Cells.Count];
                    int cellcount = 0;
                    //Convert ltr to rtl
                    foreach (DataGridViewCell Cel in GridRow.Cells)
                    {
                        _GridCell[cellcount++] = Cel;
                    }
                    //Draw Columns Contents                
                    for (int i = (_GridCell.Count() - 1); i >= 0; i--)
                    {
                        if (_GridCell[i].Value != null)
                        {
                            e.Graphics.DrawString(_GridCell[i].FormattedValue.ToString(),
                                _GridCell[i].InheritedStyle.Font,
                                new SolidBrush(_GridCell[i].InheritedStyle.ForeColor),
                                new RectangleF((int)arrColumnLefts[iCount],
                                (float)iTopMargin,
                                (int)arrColumnWidths[iCount], (float)iCellHeight),
                                strFormat);
                        }
                        //Drawing Cells Borders 
                        e.Graphics.DrawRectangle(Pens.Black,
                            new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                            (int)arrColumnWidths[iCount], iCellHeight));
                        iCount++;
                    }
                }
                iRow++;
                iTopMargin += iCellHeight;
            }
            //If more lines exist, print another page.
            if (bMorePagesToPrint)
                e.HasMorePages = true;
            else
                e.HasMorePages = false;
            //}
            //catch (Exception exc)
            //{
            //    MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK,
            //       MessageBoxIcon.Error);
            //}
        }

        private void _printDocument_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            try
            {
                strFormat = new StringFormat();
                strFormat.Alignment = StringAlignment.Center;
                strFormat.LineAlignment = StringAlignment.Center;
                strFormat.Trimming = StringTrimming.EllipsisCharacter;

                arrColumnLefts.Clear();
                arrColumnWidths.Clear();
                iCellHeight = 0;
                iRow = 0;
                bFirstPage = true;
                bNewPage = true;

                // Calculating Total Widths
                iTotalWidth = 0;
                foreach (DataGridViewColumn dgvGridCol in gw.Columns)
                {
                    iTotalWidth += dgvGridCol.Width;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

    }

For using: this will show print dialog with grid view result

ClsPrint _ClsPrint = new ClsPrint(dataGridView1, "header doc text");
 _ClsPrint.PrintForm();

Result

Further information and full example proejct

这篇关于如何从一个DataGridView控制打印值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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