Add context menu in datagrid view in winform application

How to show the context menu when right-clicking on a menu item in a DataGridView? I would like to add delete to the menu so that the entire line can be deleted. Thanks at Advance

+6
c # winforms datagridview
source share
3 answers

Regarding Miguel's answer, I think it 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]); } 
+3
source share

You need to create a context menu using the "Delete line" option in the designer. Then assign this property to the DGV (Data Grid View) ContextMenuStrip context menu.

Then double click on the delete line item and add this code:

 DGV.Rows.Remove(DGV.CurrentRow); 

You also need to add the MouseUp event for DGV, which allows the current cell to change when you right-click on it:

 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]; } 
+6
source share

I know this question is pretty old, but maybe someone will use it anyway. There is an event for this, CellContextMenuStripNeeded . The following code works fine for me and seems less hacked than MouseUp Solution:

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

All Articles