- DataTable dTable = new DataTable();
- private void Form1_Load(object sender, EventArgs e)
- {
- dTable.Columns.Add("Employee Id");
- dTable.Columns.Add("First Name");
- dTable.Columns.Add("Last Name");
- dTable.Rows.Add("1000", "John", "Smith");
- dTable.Rows.Add("1001", "Suzan", "Baker");
- dTable.Rows.Add("1002", "Jia", "Li");
- dTable.Rows.Add("1003", "Ted", "Jones");
- dTable.Rows.Add("1004", "Sonia", "Zahir");
- PrintDocument document = new PrintDocument();
- document.PrintPage += new PrintPageEventHandler(document_PrintPage);
- PrintPreviewDialog ppDialog = new PrintPreviewDialog();
- ppDialog.Document = document;
- ppDialog.Show();
- }
- void document_PrintPage(object sender, PrintPageEventArgs e)
- {
- PrintDocument document = (PrintDocument)sender;
- Graphics g = e.Graphics;
- Brush brush = new SolidBrush(Color.Black);
- Pen pen = new Pen(brush);
- Font font = new Font("Arial", 9);
- int x=0, y=0, width=150, height=30;
- foreach (DataColumn column in dTable.Columns)
- {
- g.DrawRectangle(pen, x, y, width, height);
- SizeF size = g.MeasureString(column.ColumnName, font);
- float xPadding = (width - size.Width) / 2;
- g.DrawString(column.ColumnName, font, brush, x + xPadding, y +5);
- x += width;
- }
- x = 0;
- y += 30;
- int columnCount = dTable.Columns.Count;
- foreach (DataRow row in dTable.Rows)
- {
- for (int i=0; i < columnCount; i++)
- {
- g.DrawRectangle(pen, x, y, width, height);
- SizeF size = g.MeasureString(row[i].ToString(), font);
- float xPadding = (width - size.Width) / 2;
- g.DrawString(row[i].ToString(), font, brush, x + xPadding, y + 5);
- x += width;
- }
- x = 0;
- y+=30;
- }
- }
C# - DataTable To PrintPreviewDialog
This code snippet demonstrates how to draw a table from data in a DataTable using the PrintPreviewDialog and PrintDocument classes.
No comments:
Post a Comment