Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 778
Data-Base Avatar asked Jun 14 '10 05:06

Data-Base


People also ask

How to delete row in DataGridView in c# windows application?

When the Delete Button is clicked, the DataGridView CellContentClick event handler is executed. If the ColumnIndex is 3 i.e. the Delete Button is clicked, then a Confirmation MessageBox us show and if the User clicks Yes button the Row will be deleted (removed) from DataGridView and Database Table.

How to delete row in GridView c#?

The User selects the row from the checkbox that he want to delete and on a button click it is deleted from the GridView and from the database too. Open Visual Studio 2010 and create an Empty Website, provide a suitable name (Gridview_demo). In Solution Explorer you get your empty website.


1 Answers

I finally solved it:

  • In Visual Studio, create a ContextMenuStrip with an item called "DeleteRow"

  • Then at the DataGridView link the ContextMenuStrip

Using the code below helped me getting it work.

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

Here is the cool part

private void MyDataGridView_MouseDown(object sender, MouseEventArgs e) {     if(e.Button == MouseButtons.Right)     {         var hti = MyDataGridView.HitTest(e.X, e.Y);         MyDataGridView.ClearSelection();         MyDataGridView.Rows[hti.RowIndex].Selected = true;     } }  private void DeleteRow_Click(object sender, EventArgs e) {     Int32 rowToDelete = MyDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);     MyDataGridView.Rows.RemoveAt(rowToDelete);     MyDataGridView.ClearSelection(); } 
like image 199
Data-Base Avatar answered Sep 28 '22 14:09

Data-Base