Visual Studio 2008.NET 3.0Visual Studio 2005Visual Studio 2010.NET4.NET 2.0.NET 3.5中级开发Visual Studio.NETC#
DataGridView 列显示/隐藏弹出菜单
DataGridView 列显示/隐藏弹出菜单 - 菜单样式。
引言
我需要允许我的客户能够显示/隐藏 DataGridView
中的列。
原始来源
背景
上面提到了一篇很棒的文章(感谢 Vincenzo Rossi)。它完全实现了我需要的功能。(请参阅原始文章,了解如何使用 ToolStripDropDown
和 ToolStripControlHost
类)。我唯一不喜欢的是复选框的使用 - 它看起来有些过时... 我用类似菜单的控件代替了它。
使用代码
如果您对使用代码有任何疑问,请参考原始代码。 我的补充是 UserControlMenu
和 MenuControl
对象。 您将使用 UserControlMenu
代替原始的 CheckedListBox
。 您需要定义两个事件:OnDone
和 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;
}
在 CellMouseClick
上,您需要再次使用一个新对象
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)));
}
}