仅打印包含datagridview

时间:2017-08-24 14:26:35

标签: c# datagridview

是否可以仅打印DataGridView中具有值并排除非空值的行中的列?我正在尝试打印那些并且只有那些存储了实际值的那些,但是现在它正在打印所有这些。

以下是实际打印文档的屏幕截图(另存为pdf):http://imgur.com/HiF9heq

我想删除剩下的空列。

以下是我打印的代码和填充数据表的代码:

private void Printdoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {

        try
        {
            qbcDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;


            // set the left margin of the document to be printed
            int leftMargin = e.MarginBounds.Left;

            // set the top margin of the document to be printed
            int topMargin = e.MarginBounds.Top;

            // variable to determine if more pages are to be printed
            bool printMore = false;

            // temp width
            int tmpWidth = 0;

            // for the first page to print, set the cell width and header height
            if (firstPage)
            {
                foreach (DataGridViewColumn gridCol in qbcDataGridView.Columns)
                {
                    tmpWidth = (int)(Math.Floor((double)gridCol.Width /
                        totalWidth * totalWidth *
                        ((double)e.MarginBounds.Width / totalWidth)));


                    headerHeight = (int)(e.Graphics.MeasureString(gridCol.HeaderText, gridCol.InheritedStyle.Font, tmpWidth).Height) + 2;

                    // save the width and height of the headers
                    arrayLeftColumns.Add(leftMargin);
                    arrayColWidths.Add(tmpWidth);

                    leftMargin += tmpWidth;
                }
            }


            // loop until all of the grid rows get printed
            while (row <= qbcDataGridView.Rows.Count - 1)
            { 
                DataGridViewRow gridRow = qbcDataGridView.Rows[row];

                // set the cell height
                cellHeight = gridRow.Height + 5;

                int count = 0;

                // check to see if the current page settings allow more rows to print
                if (topMargin + cellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
                {
                    newPage = true;

                    firstPage = false;

                    printMore = true;

                    break;
                }
                else
                {
                    if (newPage)
                    {
                        // draw the header
                        e.Graphics.DrawString("QBC Directory",
                            new Font(qbcDataGridView.Font, FontStyle.Bold),
                            Brushes.Black, e.MarginBounds.Left,
                            e.MarginBounds.Top - e.Graphics.MeasureString("QBC Directory",
                            new Font(qbcDataGridView.Font, FontStyle.Bold),
                            e.MarginBounds.Width).Height - 13);

                        // set the data (now) and the current time
                        String date = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();

                        // draw the date on the print document
                        e.Graphics.DrawString(date,
                            new Font(qbcDataGridView.Font, FontStyle.Bold),
                            Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - e.Graphics.MeasureString(date,
                            new Font(qbcDataGridView.Font, FontStyle.Bold),
                            e.MarginBounds.Width).Width),
                            e.MarginBounds.Top - e.Graphics.MeasureString("QBC Directory", new Font(new Font(qbcDataGridView.Font, FontStyle.Bold),
                            FontStyle.Bold), e.MarginBounds.Width).Height - 13);

                        // draw the column headers
                        topMargin = e.MarginBounds.Top;


                        foreach (DataGridViewColumn gridCol in qbcDataGridView.Columns)
                        {
                            if (!string.IsNullOrEmpty(gridCol.HeaderText))
                            {
                                // header color
                                e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
                                    new Rectangle((int)arrayLeftColumns[count], topMargin,
                                    (int)arrayColWidths[count], headerHeight));

                                // header text box
                                e.Graphics.DrawRectangle(Pens.Black,
                                    new Rectangle((int)arrayLeftColumns[count], topMargin,
                                    (int)arrayColWidths[count], headerHeight));

                                // header string
                                e.Graphics.DrawString(gridCol.HeaderText,
                                    gridCol.InheritedStyle.Font, new SolidBrush(gridCol.InheritedStyle.ForeColor),
                                    new RectangleF((int)arrayLeftColumns[count], topMargin, (int)arrayColWidths[count], headerHeight), string_format);
                            }
                            else
                            {
                                break;
                            }

                            count++;
                        }

                        newPage = false;

                        topMargin += headerHeight;
                    }

                    count = 0;

                    // draw the column's contents
                    foreach (DataGridViewCell gridCell in gridRow.Cells)
                    {
                        if (gridCell.Value != null)
                        {
                            if (!string.IsNullOrEmpty(gridCell.Value.ToString()))
                            {
                                e.Graphics.DrawString(gridCell.Value.ToString(),
                                    gridCell.InheritedStyle.Font, new SolidBrush(gridCell.InheritedStyle.ForeColor),
                                    new RectangleF((int)arrayLeftColumns[count], topMargin, (int)arrayColWidths[count], cellHeight), string_format);
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }

                        // draw the borders for the cells
                        e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)arrayLeftColumns[count], topMargin, (int)arrayColWidths[count], cellHeight));

                        count++;
                    }
                }

                row++;

                topMargin += cellHeight;

                // if more lines exist, print another page
                if (printMore)
                {
                    e.HasMorePages = true;
                }
                else
                {
                    e.HasMorePages = false;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

    }

和填充DataGridView的菜单条项:

private void MenuViewMembers_Click(object sender, EventArgs e)
        {
            qbcDataGridView.Font = new Font(qbcDataGridView.Font.FontFamily, 10);

        qbcDataGridView.Location = new Point(30, 100);

        qbcDataGridView.Size = new Size(1500, 500);

        dbConn.Open();

        DataTable dt = new DataTable();


        DbAdapter = new OleDbDataAdapter("select ID, household_head, birthday, phone, email, address, status, spouse, spouse_birthday, spouse_email, anniversary, spouse_status," +
            "child1, child1_birthday, child1_email, child2, child2_birthday, child3_birthday, child4, child4_birthday, child4_email, child5, child5_birthday, child5_email," +
            "child6, child6_birthday, child6_email, child7, child7_birthday, child7_email from members", dbConn);
        DbAdapter.Fill(dt);

        qbcDataGridView.DataSource = dt;


        qbcDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

        qbcDataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

        qbcDataGridView.DefaultCellStyle.WrapMode = DataGridViewTriState.True;


        dbConn.Close();

        Controls.Add(qbcDataGridView);
    }

我认为如果只打印非空值,它会正确格式化打印文档(见截图)。

非常感谢任何帮助。

谢谢!

更新 - 我得到了它,所以没有显示空单元格(http://imgur.com/R0ueyft),但我想我的另一个问题是如果单元格为空,如何不显示列标题。我更新了我的代码以反映我所做的更改。

3 个答案:

答案 0 :(得分:5)

使用数据填充DataTable后,请浏览列并删除空。

DbAdapter.Fill(dt);

for (int i = dt.Columns.Count - 1; i >= 0; i--)
{
    if (dt.AsEnumerable().All(row => row[i].ToString() == ""))
    {
        dt.Columns.RemoveAt(i);
    }
}

qbcDataGridView.DataSource = dt;

答案 1 :(得分:0)

这并不意味着提供一个重复的答案,但这里是Alexander Petrov的答案的增强,为了处理空数据,这可能与从数据库表中读取数据时的空字符串一样,如下:

DbAdapter.Fill(dt);

for (int i = dt.Columns.Count - 1; i >= 0; i--)
{
    if (dt.AsEnumerable().All(row => row[i] == null || row => row[i].ToString() == ""))
    {
        dt.Columns.RemoveAt(i);
    }
}

qbcDataGridView.DataSource = dt;

将IEnumerable.All方法用作documented

答案 2 :(得分:0)

如果您在datagrid中有空行,请擦除它,它将正常工作。 当循环开始并到达数据网格的末尾时,它将返回异常,因为最后一行没有值