how to print only datagridview and label thgether
how to print only datagridview and label together from the form
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Gopal MahadakPosted Feb 10, 2013, 11:32 PM
Refer Attached File
private int row = 0;
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable("testPrint");
dt.Columns.Add("Column1");
dt.Rows.Add(new object[] { "Value1"});
dataGridView.DataSource = dt;
}
private void previewButton_Click(object sender, EventArgs e)
{
printPreviewDialog.ShowDialog();
}
private void printDocument_PrintPage(object sender, PrintPageEventArgse)
{
int rowPosition = 25;
// draw headers
DrawHeader(e.Graphics, ref rowPosition);
rowPosition += 40;
// draw each row
DrawGridBody(e.Graphics, rowPosition);
// see if there are more pages to print
if(row <= 5)
e.HasMorePages = true;
else
row = 0;
}
private void DrawHeader(Graphics g, ref int y_value)
{
int x_value = 0;
Font bold = new Font(this.Font, FontStyle.Bold);
foreach(DataGridViewColumn dc in dataGridView.Columns)
{
g.DrawString(dc.HeaderText, bold, Brushes.Black,
(float)x_value, (float)y_value);
columnPosition += dc.Width + 5;
}
}
private void DrawGridBody(Graphics g, int y_value)
{
int x_value;
for(int i = 0; i < 5; ++i)
{
DataRow dr =
((DataTable)dataGridView.DataSource).Rows[i + row];
x_value = 0;
// draw a solid line
g.DrawLine(Pens.Black, new Point(0, y_value),
new Point(this.Width, y_value));
foreach(DataGridViewColumn dc in dataGridView.Columns)
{
string text = dr[dc.DataPropertyName].ToString();
g.DrawString(text, this.Font, Brushes.Black,
(float)x_value, (float)y_value + 10f);
x_value += dc.Width + 5;
}
y_value += 40;
}
row += 5;
}