[c#] Right click to select a row in a Datagridview and show a menu to delete it

I have few columns in my DataGridView, and there is data in my rows. I saw few solutions in here, but I can not combine them!

Simply a way to right-click on a row, it will select the whole row and show a menu with an option to delete the row and when the option selected it will delete the row.

I made few attempts but none is working and it looks messy. What should I do?

This question is related to c# select datagridview contextmenu right-click

The answer is


It's much more easier to add only the event for mousedown:

private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        var hti = MyDataGridView.HitTest(e.X, e.Y);
        MyDataGridView.Rows[hti.RowIndex].Selected = true;
        MyDataGridView.Rows.RemoveAt(rowToDelete);
        MyDataGridView.ClearSelection();
    }
}

This is easier. Of cource you have to init your mousedown-event as already mentioned with:

this.MyDataGridView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown);

in your constructor.


base on @Data-Base answer it will not work until make selection mode FullRow

  MyDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

but if you need to make it work in CellSelect Mode

 MyDataGridView.SelectionMode = DataGridViewSelectionMode.CellSelect;

 // for cell selection
 private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
 {
  if(e.Button == MouseButtons.Right)
    {
       var hit = MyDataGridView.HitTest(e.X, e.Y);
       MyDataGridView.ClearSelection();

       // cell selection
       MyDataGridView[hit.ColumnIndex,hit.RowIndex].Selected = true;
   }
}

private void DeleteRow_Click(object sender, EventArgs e)
{
   int rowToDelete = MyDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
   MyDataGridView.Rows.RemoveAt(rowToDelete);
   MyDataGridView.ClearSelection();
}

You can also make this a little simpler by using the following inside the event code:

private void MyDataGridView_MouseDown(object sender, MouseEventArgs e) 
{     
    if (e.Button == MouseButtons.Right)     
    {         
        rowToDelete = e.RowIndex;
        MyDataGridView.Rows.RemoveAt(rowToDelete);         
        MyDataGridView.ClearSelection();     
    } 
}

For completness of this question, better to use a Grid event rather than mouse.

First Set your datagrid properties:

SelectionMode to FullRowSelect and RowTemplate / ContextMenuStrip to a context menu.

Create the CellMouseDown event:-

private void myDatagridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        int rowSelected = e.RowIndex;
        if (e.RowIndex != -1)
        {
            this.myDatagridView.ClearSelection();
            this.myDatagridView.Rows[rowSelected].Selected = true;
        }
        // you now have the selected row with the context menu showing for the user to delete etc.
    }
}

All the answers posed in to this question are based on a mouse click event. You can also assign a ContenxtMenuStrip to your DataGridview and check if there is a row selected when the user RightMouseButtons on the DataGridView and decide whether you want to view the ContenxtMenuStrip or not. You can do so by setting the CancelEventArgs.Cancel value in the the Opening event of the ContextMenuStrip

    private void MyContextMenuStrip_Opening(object sender, CancelEventArgs e)
    {
        //Only show ContextMenuStrip when there is 1 row selected.
        if (MyDataGridView.SelectedRows.Count != 1) e.Cancel = true;
    }

But if you have several context menu strips, with each containing different options, depending on the selection, I would go for a mouse-click-approach myself as well.


It is work for me without any errors:

this.dataGridView2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown); 
this.dataGridView2.Click += new System.EventHandler(this.DeleteRow_Click);

And this

private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        var hti = dataGridView2.HitTest(e.X, e.Y);
        dataGridView2.ClearSelection();
        dataGridView2.Rows[hti.RowIndex].Selected = true;
    }

}


private void DeleteRow_Click(object sender, EventArgs e)
{
    Int32 rowToDelete = dataGridView2.Rows.GetFirstRow(DataGridViewElementStates.Selected);
    if (rowToDelete == -1) { }
    else 
    {
        dataGridView2.Rows.RemoveAt(rowToDelete);
        dataGridView2.ClearSelection();
    }
}

private void dataGridView1_CellContextMenuStripNeeded(object sender, 
DataGridViewCellContextMenuStripNeededEventArgs e)
{            
    if (e.RowIndex != -1)
    {
        dataGridView1.ClearSelection();
        this.dataGridView1.Rows[e.RowIndex].Selected = true;
        e.ContextMenuStrip = contextMenuStrip1;
    }
}

I have a new workaround to come in same result, but, with less code. for Winforms... That's example is in portuguese Follow up step by step

  1. Create a contextMenuStrip in your form and create one item
  2. Sign one event click (OnCancelarItem_Click) for this contextMenuStrip enter image description here
  3. Create a event 'UserDeletingRow' on gridview enter image description here and now... you've simulating on key press del from user

    you don't forget to enable delete on the gridview, right?!

enter image description here enter image description here and finally... enter image description here


See here it can be done using the DataGridView RowTemplate property.

Note: This code isn't tested but I've used this method before.

// Create DataGridView
DataGridView gridView = new DataGridView();
gridView.AutoGenerateColumns = false;
gridView.Columns.Add("Col", "Col");

// Create ContextMenu and set event
ContextMenuStrip cMenu = new ContextMenuStrip();
ToolStripItem mItem = cMenu.Items.Add("Delete");
mItem.Click += (o, e) => { /* Do Something */ };           

// This makes all rows added to the datagridview use the same context menu
DataGridViewRow defaultRow = new DataGridViewRow();
defaultRow.ContextMenuStrip = cMenu;

And there you go, as easy as that!


private void dgvOferty_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
    {
        dgvOferty.ClearSelection();
        int rowSelected = e.RowIndex;
        if (e.RowIndex != -1)
        {
            this.dgvOferty.Rows[rowSelected].Selected = true;
        }
        e.ContextMenuStrip = cmstrip;
    }

TADA :D. The easiest way period. For custom cells just modify a little.


private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Right)
    {
        MyDataGridView.ClearSelection();
        MyDataGridView.Rows[e.RowIndex].Selected = true;
    }
}

private void DeleteRow_Click(object sender, EventArgs e)
{
    Int32 rowToDelete = MyrDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
    MyDataGridView.Rows.RemoveAt(rowToDelete);
    MyDataGridView.ClearSelection();
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to select

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option> SQL query to check if a name begins and ends with a vowel Angular2 *ngFor in select list, set active based on string from object SQL: Two select statements in one query How to get selected value of a dropdown menu in ReactJS DATEDIFF function in Oracle How to filter an array of objects based on values in an inner array with jq? Select unique values with 'select' function in 'dplyr' library how to set select element as readonly ('disabled' doesnt pass select value on server) Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Examples related to datagridview

How to refresh or show immediately in datagridview after inserting? Delete a row in DataGridView Control in VB.NET Looping each row in datagridview How to get cell value from DataGridView in VB.Net? Changing datagridview cell color based on condition Index was out of range. Must be non-negative and less than the size of the collection parameter name:index how to bind datatable to datagridview in c# DataGridView AutoFit and Fill How to export dataGridView data Instantly to Excel on button click? Populate a datagridview with sql query results

Examples related to contextmenu

How to add a "open git-bash here..." context menu to the windows explorer? Android: How to enable/disable option menu item on button click? How to add a custom right-click menu to a webpage? Making custom right-click context menus for my web-app Right click to select a row in a Datagridview and show a menu to delete it right click context menu for datagridview How do I create a right click context menu in Java Swing? How to disable right-click context-menu in JavaScript

Examples related to right-click

Adding a right click menu to an item How to add a custom right-click menu to a webpage? Java Mouse Event Right Click Making custom right-click context menus for my web-app How to disable mouse right click on a web page? Right click to select a row in a Datagridview and show a menu to delete it right click context menu for datagridview How to distinguish between left and right mouse click with jQuery