Monday, March 2, 2009

C# - DataGridView - delete a row by context menu strip

"How to remove a data row from a DataGridView control using a context menu strip"

The following codes just show one of possible methods to do the job.

To keep the DataGridView row index which is selected by right click, we need a private variable in our form class, let's call it iDGVrow2Del. You need to drag and drop a context menu strip control to your form that we call it mnuStrp4DgvMyData too for our example. Then you should show the menu when user right click on a row in your DataGridView which we call it dgvMyData here. To find when the user does right click, you can write your code in CellMouseUp method of DataGridView and if you found a right click, just you need to keep the row index and then Show the context menu. The menu can keep just an item with "Delete Row" as its text. At last code for Click event of that menu strip object to check if the row is not an empty new row in your DataGridView then remove it using its index in iDGVrow2Del variable from your Row collection of the DataGridView. Here you go ... The simple sample code is as following:


private int iDGVrow2Del = 0;

private void dgvMyData_CellMouseUp(object sender,
DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
this.dgvMyData.Rows[e.RowIndex].Selected = true;
this.iDGVrow2Del = e.RowIndex;

this.dgvMyData.CurrentCell =
this.dgvMyData.Rows[e.RowIndex].Cells[1];

this.mnuStrp4DgvMyData.Show(this.dgvMyData, e.Location);
}
}

private void mnuStrp4DgvMyData_Click(object sender, EventArgs e)
{
if (!this.dgvMyData.Rows[this.iDGVrow2Del].IsNewRow)
this.dgvBcktSrch.Rows.RemoveAt(this.iDGVrow2Del);
}

Share/Bookmark