【问题标题】:How to get the column index of a DataGridView through click of ContextMenu in Winforms?如何通过单击Winforms中的ContextMenu获取DataGridView的列索引?
【发布时间】:2014-01-29 09:18:32
【问题描述】:

我有一个 9 列的 DataGridView。 我为所有列标题添加了相同的ContextMenuStrip

dataGridView.Columns[i].HeaderCell.ContextMenuStrip = myContextMenuStrip;

myContextMenuStrip 包含一个名为“隐藏列”的项目。

现在,我有一个hidecolumnClick 事件的事件处理程序,我想找出在事件处理程序中单击了哪个列标题? 有没有办法做到这一点?

【问题讨论】:

  • 什么是发件人参数?数据网格或单元格?如果是单元格,则查找单元格的列。

标签: c# .net winforms visual-studio-2010 datagridview


【解决方案1】:

订阅DataGridView.CellMouseDown 事件。在事件处理程序中,存储列索引或显示所需的上下文菜单。

示例代码:

void datagridview1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        //get the RowIndex or ColumnIndex from the event argument
    }
}

【讨论】:

    【解决方案2】:

    您好,如果您想对所有标题使用相同的 ContextMenu 对象,我想出了另一个解决方案。看看吧。。

    在Grid上绑定CellMouseDown事件-

    dataGridView1.CellMouseDown += new DataGridViewCellMouseEventHandler(dataGridView1_CellMouseDown);
    

    并在 cellmousedown 中设置点击列的值如下 -

    int columnClicked = -1;
    
    void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
         columnClicked = e.ColumnIndex;
    }
    

    现在您可以访问上下文菜单项单击事件中的列单击值,如下所示

    private void helloToolStripMenuItem_Click(object sender, EventArgs e)
    {
        MessageBox.Show(columnClicked.ToString());
    }
    

    除了你已经将上下文菜单分配给标题..

    如果你愿意,我也可以给你样品..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-18
      • 2012-11-06
      • 1970-01-01
      • 2017-10-09
      相关资源
      最近更新 更多