This tutorial will show you how to delete rows in a DataGridView by right-clicking, then selecting delete from the menu in C#.NET Winforms
Suppose you have a form with a DataGridView filled in with data. You need to drag a ContextMenuStrip control from your visual toolbox into your windows forms application, then add a click event handler to ContextMenuStrip
You should create a local variable to store the index row, by default your index variable row is set to zero
private int rowIndex = 0;
Add the code to handle your ContextMenuStrip_Click event as shown below
private void contextMenuStrip1_Click(object sender, EventArgs e)
{
if (!this.dataGridView1.Rows[this.rowIndex].IsNewRow)
this.dataGridView1.Rows.RemoveAt(this.rowIndex);
}
You can also delete existing rows by using the binding source control
Next, Add the code to handle the menu that is displayed when right-clicking on your DataGridView like the following
private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
dataGridView1.Rows[e.RowIndex].Selected = true;
rowIndex = e.RowIndex;
dataGridView1.CurrentCell = this.dataGridView1.Rows[e.RowIndex].Cells[1];
contextMenuStrip1.Show(this.dataGridView1, e.Location);
contextMenuStrip1.Show(Cursor.Position);
}
}
You should set the rowIndex variable to the current row