A DataGridView Column Show/Hide Popup - Menu Style
A DataGridView column show/hide popup - Menu style.
Introduction
I needed to allow my customers to be able to show/hide columns in a DataGridView
.
Original source
Background
There is a great article mentioned above (Thank you Vincenzo Rossi). It does exactly what I needed to do. (Please see the original article on how to use the ToolStripDropDown
and ToolStripControlHost
classes). The only thing I did not like - the usage of the check boxes - it seems to be old-fashioned... I replaced that with a menu-like control.
Using the code
Please refer to the original code if you have any questions regarding using the code. My additions are the UserControlMenu
and MenuControl
objects. Instead of using the original CheckedListBox
, you will use UserControlMenu
. You will need to define two events: OnDone
and CheckedChangedEnent
:
UserControlMenu pUserControl1 = new UserControlMenu();
public DataGridViewColumnSelector() {
//mCheckedListBox = new CheckedListBox();
//mCheckedListBox.CheckOnClick = true;
//mCheckedListBox.ItemCheck +=
// new ItemCheckEventHandler(mCheckedListBox_ItemCheck);
//ToolStripControlHost mControlHost = new ToolStripControlHost(mCheckedListBox);
pUserControl1.DoneEvent += new EventHandler(OnDone);
pUserControl1.CheckedChangedEnent +=
new UserControlMenu.CheckedChanged(CheckedChangedEnent);
ToolStripControlHost mControlHost = new ToolStripControlHost(pUserControl1);
...
}
void CheckedChangedEnent(int iIndex, bool bChecked)
{
mDataGridView.Columns[iIndex].Visible = bChecked;
}
private void OnDone(object sender, EventArgs e)
{
mPopup.AutoClose = false;
mPopup.Close();
mPopup.AutoClose = true;
}
On CellMouseClick
, you will need to use a new object one more time:
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;
pUserControl1.Initialize(mDataGridView);
mPopup.Show(mDataGridView.PointToScreen(new Point (e.X,e.Y)));
}
}