Hi smile,
Refer below sample.
C#
Class
class DataGridViewColumnSelector
{
private DataGridView mDataGridView = null;
private CheckedListBox mCheckedListBox;
private ToolStripDropDown mPopup;
public int MaxHeight = 300;
public int Width = 200;
public DataGridView DataGridView
{
get { return mDataGridView; }
set
{
if (mDataGridView != null)
mDataGridView.CellMouseClick -= new DataGridViewCellMouseEventHandler(mDataGridView_CellMouseClick);
mDataGridView = value;
if (mDataGridView != null)
mDataGridView.CellMouseClick += new DataGridViewCellMouseEventHandler(mDataGridView_CellMouseClick);
}
}
void mDataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
//if (e.Button == MouseButtons.Right && e.RowIndex == -1 && e.ColumnIndex == -1)
if (e.Button == MouseButtons.Right)
{
mCheckedListBox.Items.Clear();
foreach (DataGridViewColumn c in mDataGridView.Columns)
{
mCheckedListBox.Items.Add(c.HeaderText, c.Visible);
}
int PreferredHeight = (mCheckedListBox.Items.Count * 16) + 15;
mCheckedListBox.Height = (PreferredHeight < MaxHeight) ? PreferredHeight : MaxHeight;
mCheckedListBox.Width = this.Width;
mPopup.Show(mDataGridView.PointToScreen(new Point(e.X, e.Y)));
}
}
public DataGridViewColumnSelector()
{
mCheckedListBox = new CheckedListBox();
mCheckedListBox.CheckOnClick = true;
mCheckedListBox.ItemCheck += new ItemCheckEventHandler(mCheckedListBox_ItemCheck);
ToolStripControlHost mControlHost = new ToolStripControlHost(mCheckedListBox);
mControlHost.Padding = Padding.Empty;
mControlHost.Margin = Padding.Empty;
mControlHost.AutoSize = false;
mPopup = new ToolStripDropDown();
mPopup.Padding = Padding.Empty;
mPopup.Items.Add(mControlHost);
}
public DataGridViewColumnSelector(DataGridView dgv) : this()
{
this.DataGridView = dgv;
}
void mCheckedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
mDataGridView.Columns[e.Index].Visible = (e.NewValue == CheckState.Checked);
}
}
Namespaces
using System.Data;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
Code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.DisplayData();
}
private void DisplayData()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] {
new DataColumn("Id"),
new DataColumn("Name"),
new DataColumn("Country") });
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.dGVAcademic.DataSource = dt;
this.dGVAcademic.ReadOnly = true;
DataGridViewColumnSelector cs = new DataGridViewColumnSelector(this.dGVAcademic);
cs.MaxHeight = 100;
cs.Width = 110;
}
private void btnexport_Click(object sender, EventArgs e)
{
if (dGVAcademic.Rows.Count > 0)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "PDF (*.pdf)|*.pdf";
sfd.FileName = "Output.pdf";
bool fileError = false;
if (sfd.ShowDialog() == DialogResult.OK)
{
if (File.Exists(sfd.FileName))
{
try
{
File.Delete(sfd.FileName);
}
catch (IOException ex)
{
fileError = true;
MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);
}
}
if (!fileError)
{
try
{
int count = 0;
foreach (DataGridViewColumn column in dGVAcademic.Columns)
{
if (column.Visible)
{
count++;
}
}
PdfPTable pdfTable = new PdfPTable(count);
pdfTable.DefaultCell.Padding = 3;
pdfTable.WidthPercentage = 100;
pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
foreach (DataGridViewColumn column in dGVAcademic.Columns)
{
if (column.Visible)
{
PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
pdfTable.AddCell(cell);
}
}
foreach (DataGridViewRow row in dGVAcademic.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Value != null && cell.Visible)
{
pdfTable.AddCell(cell.Value.ToString());
}
}
}
using (FileStream stream = new FileStream(sfd.FileName, FileMode.Create))
{
Document pdfDoc = new Document(PageSize.A4, 10f, 20f, 20f, 10f);
PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
pdfDoc.Add(pdfTable);
pdfDoc.Close();
stream.Close();
}
MessageBox.Show("Data Exported Successfully !!!", "Info");
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.Message);
}
}
}
}
else
{
MessageBox.Show("No Record To Export !!!", "Info");
}
}
}
VB.Net
Class
Public Class DataGridViewColumnSelector
Private mDataGridView As DataGridView = Nothing
Private mCheckedListBox As CheckedListBox
Private mPopup As ToolStripDropDown
Public MaxHeight As Integer = 300
Public Width As Integer = 200
Public Property DataGridView As DataGridView
Get
Return mDataGridView
End Get
Set(ByVal value As DataGridView)
If mDataGridView IsNot Nothing Then
RemoveHandler mDataGridView.CellMouseClick, AddressOf mDataGridView_CellMouseClick
End If
mDataGridView = value
If mDataGridView IsNot Nothing Then
AddHandler mDataGridView.CellMouseClick, AddressOf mDataGridView_CellMouseClick
End If
End Set
End Property
Private Sub mDataGridView_CellMouseClick(ByVal sender As Object, ByVal e As DataGridViewCellMouseEventArgs)
'If e.Button = MouseButtons.Right AndAlso e.RowIndex = -1 AndAlso e.ColumnIndex = -1 Then
If e.Button = MouseButtons.Right Then
mCheckedListBox.Items.Clear()
For Each c As DataGridViewColumn In mDataGridView.Columns
mCheckedListBox.Items.Add(c.HeaderText, c.Visible)
Next
Dim PreferredHeight As Integer = (mCheckedListBox.Items.Count * 16) + 15
mCheckedListBox.Height = If((PreferredHeight < MaxHeight), PreferredHeight, MaxHeight)
mCheckedListBox.Width = Me.Width
mPopup.Show(mDataGridView.PointToScreen(New Point(e.X, e.Y)))
End If
End Sub
Public Sub New()
mCheckedListBox = New CheckedListBox()
mCheckedListBox.CheckOnClick = True
AddHandler mCheckedListBox.ItemCheck, AddressOf mCheckedListBox_ItemCheck
Dim mControlHost As ToolStripControlHost = New ToolStripControlHost(mCheckedListBox)
mControlHost.Padding = Padding.Empty
mControlHost.Margin = Padding.Empty
mControlHost.AutoSize = False
mPopup = New ToolStripDropDown()
mPopup.Padding = Padding.Empty
mPopup.Items.Add(mControlHost)
End Sub
Public Sub New(ByVal dgv As DataGridView)
Me.New()
Me.DataGridView = dgv
End Sub
Private Sub mCheckedListBox_ItemCheck(ByVal sender As Object, ByVal e As ItemCheckEventArgs)
mDataGridView.Columns(e.Index).Visible = (e.NewValue = CheckState.Checked)
End Sub
End Class
Namespaces
Imports System.IO
Imports System.Data
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Code
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.DisplayData()
End Sub
Private Sub DisplayData()
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn(2) {
New DataColumn("Id"),
New DataColumn("Name"),
New DataColumn("Country")})
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.dGVAcademic.DataSource = dt
Me.dGVAcademic.ReadOnly = True
Dim cs As DataGridViewColumnSelector = New DataGridViewColumnSelector(Me.dGVAcademic)
cs.MaxHeight = 100
cs.Width = 110
End Sub
Private Sub btnexport_Click(sender As Object, e As EventArgs) Handles btnexport.Click
If dGVAcademic.Rows.Count > 0 Then
Dim sfd As SaveFileDialog = New SaveFileDialog()
sfd.Filter = "PDF (*.pdf)|*.pdf"
sfd.FileName = "Output.pdf"
Dim fileError As Boolean = False
If sfd.ShowDialog() = DialogResult.OK Then
If File.Exists(sfd.FileName) Then
Try
File.Delete(sfd.FileName)
Catch ex As IOException
fileError = True
MessageBox.Show("It wasn't possible to write the data to the disk." & ex.Message)
End Try
End If
If Not fileError Then
Try
Dim count As Integer = 0
For Each column As DataGridViewColumn In dGVAcademic.Columns
If column.Visible Then
count += 1
End If
Next
Dim pdfTable As PdfPTable = New PdfPTable(count)
pdfTable.DefaultCell.Padding = 3
pdfTable.WidthPercentage = 100
pdfTable.HorizontalAlignment = Element.ALIGN_LEFT
For Each column As DataGridViewColumn In dGVAcademic.Columns
If column.Visible Then
Dim cell As PdfPCell = New PdfPCell(New Phrase(column.HeaderText))
pdfTable.AddCell(cell)
End If
Next
For Each row As DataGridViewRow In dGVAcademic.Rows
For Each cell As DataGridViewCell In row.Cells
If cell.Value IsNot Nothing AndAlso cell.Visible Then
pdfTable.AddCell(cell.Value.ToString())
End If
Next
Next
Using stream As FileStream = New FileStream(sfd.FileName, FileMode.Create)
Dim pdfDoc As Document = New Document(PageSize.A4, 10.0F, 20.0F, 20.0F, 10.0F)
PdfWriter.GetInstance(pdfDoc, stream)
pdfDoc.Open()
pdfDoc.Add(pdfTable)
pdfDoc.Close()
stream.Close()
End Using
MessageBox.Show("Data Exported Successfully !!!", "Info")
Catch ex As Exception
MessageBox.Show("Error :" & ex.Message)
End Try
End If
End If
Else
MessageBox.Show("No Record To Export !!!", "Info")
End If
End Sub
End Class
Screenshot