简体   繁体   English

在winform应用程序的数据网格视图中添加上下文菜单

[英]Add context menu in a datagrid view in a winform application

How to show a Context Menu when you right click a Menu Item in a DataGridView ? 右键单击DataGridView中的菜单项时如何显示上下文菜单? I would like to add delete in the menu so that the entire row can be deleted . 我想在菜单中添加删除,以便删除整行。 Thanks in Advance 提前致谢

You'll need to create a context menu with a "delete row" option in the designer. 您需要在设计器中创建一个带有“删除行”选项的上下文菜单。 Then assign the DGV (Data Grid View)'s ContextMenuStrip property to this context menu. 然后将DGV(数据网格视图)的ContextMenuStrip属性分配给此上下文菜单。

Then double click on the delete row item, and add this code: 然后双击删除行项,并添加以下代码:

DGV.Rows.Remove(DGV.CurrentRow);

You'll also need to add a MouseUp event for the DGV that allows the current cell to change when you right click it: 您还需要为DGV添加MouseUp事件,以便在您右键单击时允许更改当前单元格:

private void DGV_MouseUp(object sender, MouseEventArgs e)
{
    // This gets information about the cell you clicked.
    System.Windows.Forms.DataGridView.HitTestInfo ClickedInfo = DGV.HitTest(e.X, e.Y);

    // This is so that the header row cannot be deleted
    if (ClickedInfo.ColumnIndex >= 0 && ClickedInfo.RowIndex >= 0)

    // This sets the current row
    DataViewMain.CurrentCell = DGV.Rows[ClickedInfo.RowIndex].Cells[ClickedInfo.ColumnIndex];
}

I know this question is quite old, but maybe someone will still have use for this. 我知道这个问题已经很老了,但也许有人会对此有所帮助。 There is an Event for this, CellContextMenuStripNeeded . 有一个事件, CellContextMenuStripNeeded The following code works perfectly for me and seems less hacky than the MouseUp Solution: 下面的代码对我来说非常适合,而且看起来比MouseUp解决方案更糟糕:

private void DGV_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
{
    if (e.RowIndex >= 0)
    {
        DGV.ClearSelection();
        DGV.Rows[e.RowIndex].Selected = true;
        e.ContextMenuStrip = MENUSTRIP;
    }
}

With reference to Miguel answer 参考米格尔的答案
I think this will be easy to implement like this 我认为这样很容易实现

    int currentRowIndex;
    private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
    {
        currentRowIndex = e.RowIndex;
    }  
    private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
    {    
        dataGridView1.Rows.Remove(dataGridView1.Rows[currentRowIndex]);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM