Introduction
I needed to allow my customers to be able to show/hide columns in a DataGridView
.
Original source
DGVColumnSelector.aspx.
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() {
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) {
pUserControl1.Initialize(mDataGridView);
mPopup.Show(mDataGridView.PointToScreen(new Point (e.X,e.Y)));
}
}