65.9K
CodeProject 正在变化。 阅读更多。
Home

DataGridView 列显示/隐藏弹出菜单

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.65/5 (10投票s)

2009 年 9 月 1 日

CPOL
viewsIcon

73487

downloadIcon

3994

DataGridView 列显示/隐藏弹出菜单 - 菜单样式。

引言

我需要允许我的客户能够显示/隐藏 DataGridView 中的列。

原始来源

DGVColumnSelector.aspx.

背景

上面提到了一篇很棒的文章(感谢 Vincenzo Rossi)。它完全实现了我需要的功能。(请参阅原始文章,了解如何使用 ToolStripDropDownToolStripControlHost 类)。我唯一不喜欢的是复选框的使用 - 它看起来有些过时... 我用类似菜单的控件代替了它。

使用代码

如果您对使用代码有任何疑问,请参考原始代码。 我的补充是 UserControlMenuMenuControl 对象。 您将使用 UserControlMenu 代替原始的 CheckedListBox。 您需要定义两个事件:OnDoneCheckedChangedEnent

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)));
    }
}
© . All rights reserved.