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

Last Reply 14 days ago By dharmendr

Posted 18 days 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;
        }

 

You are viewing reply posted by: dharmendr 14 days ago.
Posted 14 days 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