Dynamically Show Hide DataGridView Column using C# and VB.Net in Windows Application

Last Reply 8 months ago By dharmendr

Posted 8 months ago

I want to make show and hide column in window form. I visited many sites and found the following url which matches with my requirements.

A DataGridView Column Show/Hide Popup

I am unable to implement it in my own side and facing issues.

pls guide me how to do?

    class DataGridViewColumnSelector
    {
        // the DataGridView to which the DataGridViewColumnSelector is attached   https://www.codeproject.com/Articles/31987/A-DataGridView-Column-Show-Hide-Popup
        private DataGridView mDataGridView = null;
        // a CheckedListBox containing the column header text and checkboxes
        private CheckedListBox mCheckedListBox;
        // a ToolStripDropDown object used to show the popup
        private ToolStripDropDown mPopup;
 
        /// <summary>
        /// The max height of the popup
        /// </summary>
        public int MaxHeight = 300;
        /// <summary>
        /// The width of the popup
        /// </summary>
        public int Width = 200;
 
        /// <summary>
        /// Gets or sets the DataGridView to which the DataGridViewColumnSelector is attached
        /// </summary>
        public DataGridView DataGridView
        {
            get { return mDataGridView; }
            set
            {
                // If any, remove handler from current DataGridView
                if (mDataGridView != null) mDataGridView.CellMouseClick -= new DataGridViewCellMouseEventHandler(mDataGridView_CellMouseClick);
                // Set the new DataGridView
                mDataGridView = value;
                // Attach CellMouseClick handler to DataGridView
                if (mDataGridView != null) mDataGridView.CellMouseClick += new DataGridViewCellMouseEventHandler(mDataGridView_CellMouseClick);
            }
        }
 
        // When user right-clicks the cell origin, it clears and fill the CheckedListBox with
        // columns header text. Then it shows the popup.
        // In this way the CheckedListBox items are always refreshed to reflect changes occurred in
        // DataGridView columns (column additions or name changes and so on).
        void mDataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && e.RowIndex == -1 && e.ColumnIndex == -1)
            {
                mCheckedListBox.Items.Clear();
                foreach (DataGridViewColumn c in mDataGridView.Columns)
                {
                    mCheckedListBox.Items.Add(c.HeaderText, c.Visible);
                }
                int PreferredHeight = (mCheckedListBox.Items.Count * 16) + 7;
                mCheckedListBox.Height = (PreferredHeight < MaxHeight) ? PreferredHeight : MaxHeight;
                mCheckedListBox.Width = this.Width;
                mPopup.Show(mDataGridView.PointToScreen(new Point(e.X, e.Y)));
            }
        }
 
        // The constructor creates an instance of CheckedListBox and ToolStripDropDown.
        // the CheckedListBox is hosted by ToolStripControlHost, which in turn is
        // added to ToolStripDropDown.
        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;
        }
 
        // When user checks / unchecks a checkbox, the related column visibility is
        // switched.
        void mCheckedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            mDataGridView.Columns[e.Index].Visible = (e.NewValue == CheckState.Checked);
        }
    }

 then call this class as following behind button event

        private void DisplayData()
        { 
            con = new SqlDbConnect();
            con.SqlQuery("select YearID 'ID',AcademicName from tblAcademicYear order by YearID desc;");
            paging.SelectCommand = con.Cmd;
            sBuilder = new SqlCommandBuilder(paging);
            ds = new DataSet();
            paging.Fill(ds, "tblAcademicYear");
            sTable = ds.Tables["tblAcademicYear"];
            dGVAcademic.DataSource = ds.Tables["tblAcademicYear"].DefaultView;
            dGVAcademic.ReadOnly = true; 
            DataGridViewColumnSelector cs = new DataGridViewColumnSelector(dGVAcademic);
            cs.MaxHeight = 100;
            cs.Width = 110;
        }

 

Posted 8 months ago

Hi smile,

Check this example. Now please take its reference and correct your code.

On right click of DataGridView cell popup will open with column name and CheckBox for show hide the columns. 

DataGridViewColumnSelector

C#

class DataGridViewColumnSelector
{
    // the DataGridView to which the DataGridViewColumnSelector is attached
    private DataGridView mDataGridView = null;
    // a CheckedListBox containing the column header text and checkboxes
    private CheckedListBox mCheckedListBox;
    // a ToolStripDropDown object used to show the popup
    private ToolStripDropDown mPopup;

    public int MaxHeight = 300;
    public int Width = 200;

    public DataGridView DataGridView
    {
        get { return mDataGridView; }
        set
        {
            // If any, remove handler from current DataGridView
            if (mDataGridView != null)
                mDataGridView.CellMouseClick -= new DataGridViewCellMouseEventHandler(mDataGridView_CellMouseClick);
            mDataGridView = value;
            // Attach CellMouseClick handler to DataGridView
            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);
    }
}

VB.Net

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

Form

C#

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;
    }
}

VB.Net

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
End Class

Screenshot


Posted 8 months ago
dharmendr says:
 int PreferredHeight = (mCheckedListBox.Items.Count * 16) + 15;
            mCheckedListBox.Height = (PreferredHeight < MaxHeight) ? PreferredHeight : MaxHeight;

Change above line with below.

int PreferredHeight = (mCheckedListBox.Items.Count * 18) + 20;
mCheckedListBox.Height = PreferredHeight;

VB.Net

dharmendr says:
Dim PreferredHeight As Integer = (mCheckedListBox.Items.Count * 16) + 15
            mCheckedListBox.Height = If((PreferredHeight < MaxHeight), PreferredHeight, MaxHeight)

Change above line with below.

Dim PreferredHeight As Integer = (mCheckedListBox.Items.Count * 18) + 20
mCheckedListBox.Height = PreferredHeight