Hi ashishk,
Check this example. Now please take its reference and correct your code.
Form1.Designer.cs
Form1.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.BindDataGridView();
}
private void BindDataGridView()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country",typeof(string)) });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
this.dataGridView1.DataSource = dt;
}
Bitmap bitmap;
private void btnPrint_Click(object sender, EventArgs e)
{
btnPrint.Visible = false;
this.Controls.Add(pnlDetails);
Graphics grp = pnlDetails.CreateGraphics();
Size formSize = this.ClientSize;
bitmap = new Bitmap(formSize.Width, formSize.Height, grp);
grp = Graphics.FromImage(bitmap);
Point panelLocation = PointToScreen(pnlDetails.Location);
grp.CopyFromScreen(panelLocation.X, panelLocation.Y, 0, 0, formSize);
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.PrintPreviewControl.Zoom = 1;
printPreviewDialog1.ShowDialog();
btnPrint.Visible = false;
}
private void PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
btnPrint.Visible = false;
e.Graphics.DrawImage(bitmap, 0, 0);
}
}
Form1.vb
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
BindDataGridView()
End Sub
Private Sub BindDataGridView()
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Country", GetType(String))})
dt.Rows.Add(1, "John Hammond", "United States")
dt.Rows.Add(2, "Mudassar Khan", "India")
dt.Rows.Add(3, "Suzanne Mathews", "France")
dt.Rows.Add(4, "Robert Schidner", "Russia")
Me.dataGridView1.DataSource = dt
End Sub
Private bitmap As Bitmap
Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
Me.Controls.Add(pnlUserDetail)
Dim grp As Graphics = pnlUserDetail.CreateGraphics()
Dim formSize As Size = Me.ClientSize
bitmap = New Bitmap(formSize.Width, formSize.Height, grp)
grp = Graphics.FromImage(bitmap)
Dim panelLocation As Point = PointToScreen(pnlUserDetail.Location)
grp.CopyFromScreen(panelLocation.X, panelLocation.Y, 0, 0, formSize)
printPreviewDialog1.Document = printDocument1
printPreviewDialog1.PrintPreviewControl.Zoom = 1
printPreviewDialog1.ShowDialog()
End Sub
Private Sub PrintPage(sender As Object, e As System.Drawing.Printing.PrintPageEventArgs) Handles printDocument1.PrintPage
e.Graphics.DrawImage(bitmap, 0, 0)
End Sub
Screenshot