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

Ana*_*nth 6 .net c# datagridview winforms

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

Mig*_*ell 6

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

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

DGV.Rows.Remove(DGV.CurrentRow);
Run Code Online (Sandbox Code Playgroud)

您还需要为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];
}
Run Code Online (Sandbox Code Playgroud)


Jav*_*ram 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]);
    }
Run Code Online (Sandbox Code Playgroud)