Click here to Skip to main content
15,881,424 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi i am trying to print datagridview using print dialog. it works fine when the data is filled in the grid. but if i print the datagrid without the data datagrid use to disappear. in the same if i load data to grid it does not show me my grid. but calculation are performed perfectly.

[posted as solution by OP]
Quote:
only solution i found to restrict the problem to occur is checking if any row exist in the grid. then print else popup message for asking to fill the grid first. is there any other solution besides this please let me know.


What I have tried:

this is the code that i am using for printing the datagridview
Bitmap bitmap;
        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                int height = grdSpanSale.Height;
                grdSpanSale.Height = grdSpanSale.RowCount * grdSpanSale.RowTemplate.Height;

                //Create a Bitmap and draw the DataGridView on it.
                bitmap = new Bitmap(this.grdSpanSale.Width, this.grdSpanSale.Height);
                grdSpanSale.DrawToBitmap(bitmap, new Rectangle(0, 0, this.grdSpanSale.Width, this.grdSpanSale.Height));

                //Resize DataGridView back to original height.
                grdSpanSale.Height = height;

                //Show the Print Preview Dialog.
                printPreviewDialog1.Document = printDocument1;
                printPreviewDialog1.PrintPreviewControl.Zoom = 1;
                printPreviewDialog1.ShowDialog();
            }
            catch/*(Exception exec)*/
            {
                fromTOdate();
                //MessageBox.Show(exec.ToString());
            }
        }
        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(bitmap, 0, 0);
        }
Posted
Updated 22-Jun-19 8:51am
v2

1 solution

You're "recalculating" the grid height based on the "row count"; and you "toss" the grid's actual height. The result should be obvious. Pick a height to use as a "constant" if there are "zero" rows instead of "zero height".

int height = grdSpanSale.Height;
grdSpanSale.Height = grdSpanSale.RowCount * grdSpanSale.RowTemplate.Height;

//Create a Bitmap and draw the DataGridView on it.
bitmap = new Bitmap(this.grdSpanSale.Width, this.grdSpanSale.Height);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900