Right click in DataGridView

syntia.wijaya

Member
Joined
Apr 22, 2007
Messages
24
Location
Indonesia
Programming Experience
Beginner
Hi,

I'm trying to delete rows in datagridview using right click. So, when right click in the row, the row will be highlighted and delete menu will show.

Can anyone help?

Thanks in advance..
 
Define a ContextMenuStrip that contains a delete item.

The code behind for the delete item should loop all the selected rows, deleting them.

Additionally, i find it sensible and logical to add a CellMouseDown event handler. The following code is in C# but should be readable enough:


VB.NET:
    private void MyDataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
      try {
        [B]//if the user clicked right and also there is an existing selection but the user did NOT [/B]
[B]          //right click inside that selection[/B]
        if(e.Button == MouseButtons.Right &&
          !MyDataGridView.SelectedCells.Contains(MyDataGridView[e.ColumnIndex, e.RowIndex]))
          [B]//then set the new current cell to where the user clicked, before the menu shows[/B]          
          MyDataGridView.CurrentCell = MyDataGridView[e.ColumnIndex, e.RowIndex];
      } catch(Exception) {
        [B]//some places like headers cant be right clicked and crash the app[/B]
MessageBox.Show("Dont click there");
      }
    }

I bolded the comments
 
Back
Top