2010-11-17 43 views

回答

3

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

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

您需要在设计器中创建一个带有 “删除行”选项的上下文菜单。然后将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(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]; 
} 
+0

+1 for *“然后将DGV(数据网格视图)的** ContextMenuStrip属性**分配到该上下文菜单。”* – 2012-10-16 00:53:43

3

我知道这个问题已经很老了,但也许有人仍然会使用它。这是一个事件,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; 
    } 
} 
+0

也不需要检查if(e.RowIndex> = 0)因为该事件是由一行中或另一行中的单元触发的。所以'e.RowIndex> = 0'将始终为真。 – 2014-01-02 22:44:40

+0

请注意,这与MouseDown事件和其他类似事件的行为不同:在这种情况下,当用户使用鼠标在标题行上操作并给出'e.Rowindex = -1'时,也会触发该事件。 – 2014-01-02 22:54:34

+0

这应该是公认的答案,这是达到预期结果的预期方式。 – 2014-02-24 12:42:58