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

右键单击DataGridView中的菜单项时如何显示上下文菜单? 我想在菜单中添加删除,以便删除整行。 提前致谢

参考米格尔回答
我认为这样很容易实现

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]); } 

您需要在设计器中创建一个带有“删除行”选项的上下文菜单。 然后将DGV(数据网格视图)的ContextMenuStrip属性分配给此上下文菜单。

然后双击删除行项,并添加以下代码:

 DGV.Rows.Remove(DGV.CurrentRow); 

您还需要为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(eX, eY); // 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]; } 

我知道这个问题已经很老了,但也许有人仍然可以使用它。 有一个事件, CellContextMenuStripNeeded 。 下面的代码对我来说非常合适,而且看起来比MouseUp解决方案更少hacky:

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