繁体   English   中英

仅打印具有来自 datagridview 的值的行中的列

[英]Printing only columns in rows that have values from a datagridview

是否可以只打印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 ),但我想我的另一个问题是如果单元格为空,如何不显示列标题。 我更新了我的代码以反映我所做的更改。

用数据填充 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;

并不是要提供重复的答案,而是对 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 方法的用法记录在案

伙计们,如果你在数据网格中有那个空行,只需擦除它,它就会正常工作。 当循环开始并到达数据网格的末尾时,它将返回一个异常,因为最后一行没有值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM