How to see the preview of data grid view in Window forms
Visual Studio->New project->Window Form Application
Step 1:
Drag and place DataGridView on the form and bind it with a datatable
Step 2:
Place one button and name it Preview, generate it's click event by double clicking on it We will use this event to see preview.
Step 3:
Add Print Preview Dialog control to the Form
Step 4:
Put Print Document control from toolbox under printing tab, Double click on it to generate it's PrintPage event.
Then The Form[design] looks like this
Write the code behind as follows:
Form.cs
DEMO:
Visual Studio->New project->Window Form Application
Step 1:
Drag and place DataGridView on the form and bind it with a datatable
Step 2:
Place one button and name it Preview, generate it's click event by double clicking on it We will use this event to see preview.
Step 3:
Add Print Preview Dialog control to the Form
Step 4:
Put Print Document control from toolbox under printing tab, Double click on it to generate it's PrintPage event.
Then The Form[design] looks like this
Write the code behind as follows:
Form.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace previewdatagridview
{
public partial class Form1 : Form
{
SqlConnection con = new
SqlConnection("Data
Source=Shailaja;Initial Catalog=Peers;User Id=sa;Password=123");
public Form1()
{
InitializeComponent();
SqlDataAdapter da = new
SqlDataAdapter("Select
* from emp", con);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
private void
button1_Click(object sender, EventArgs e)
{
printPreviewDialog1.Document
= printDocument1;
printPreviewDialog1.PrintPreviewControl.Zoom = 1;
printPreviewDialog1.ShowDialog();
}
private void
printDocument1_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs
e)
{
Bitmap dataGridViewImage = new Bitmap(this.dataGridView1.Width, this.dataGridView1.Height);
dataGridView1.DrawToBitmap(dataGridViewImage, new
Rectangle(0, 0, this.dataGridView1.Width,
this.dataGridView1.Height));
e.Graphics.DrawImage(dataGridViewImage, 0, 0);
}
}
}
No comments:
Post a Comment