Tuesday, June 1, 2010

Printing Data View Grids in C#



Printing DataView Grids are tricky in C#/.NET. You can either use a draw String command or can convert the image to a bitmap. Either will print out just fine.  I suggest the latter for bigger grids, because it actually propagates through the data it looks a bit more formatted. I've recently integrated into my RPK (Remote Process Killer) Application.



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



    /* Bitmap bm = new Bitmap(this.dataGridViewResults.Width, this.dataGridViewResults.Height);
            this.dataGridViewResults.DrawToBitmap(bm, new Rectangle(0, 0, this.dataGridViewResults.Width, this.dataGridViewResults.Height));
            e.Graphics.DrawImage(bm, 0, 0);*/
       }



 private void ThePrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
       
            Font f = new Font("Arial", 6, FontStyle.Underline);
            Brush b = Brushes.DarkRed;
                e.Graphics.DrawString("Device Name" +
                    "\t\t\t" + "Process Name" + "\t\t\t\t" 
                    + " Command Line", f, b, 5, 0 * 10);
            f = new Font("Arial", 6, FontStyle.Regular);
            b = Brushes.Black;
           
 for (int i = 0; i < dataGridViewResults.Rows.Count; i++)
                {
                    try
                    {
                        e.Graphics.DrawString(
                            dataGridViewResults[6, i].Value.ToString() + "\t\t" +
                            dataGridViewResults[1, i].Value.ToString() + "\t\t\t\t" + 
                            dataGridViewResults[8, i].Value.ToString(), 
                            f, b, 5, (i + 1) * 10);
                    }
                    catch
                    {
                    }
                }
        }

No comments:

Post a Comment