Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a selected DataGridViewRow and update a connected database table?

I have a DataGridView control on a Windows Forms application (written with C#).

What I need is: when a user selects a DataGridViewRow, and then clicks on a 'Delete' button, the row should be deleted and next, the database needs to be updated using table adapters.

This is what I have so far:

private void btnDelete_Click(object sender, EventArgs e) {     if (this.dataGridView1.SelectedRows.Count > 0)     {         dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);     }                 } 

Furthermore, this only deletes one row. I would like it where the user can select multiple rows.

like image 719
Woody Avatar asked Jan 18 '10 06:01

Woody


People also ask

How to delete DataGridView rows?

Right click to select row in dataGridViewThen you create a menu item "Delete Row" in the contextMenuStrip.

How to delete row from 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.


2 Answers

This code removes selected items of dataGridView1:

 private void btnDelete_Click(object sender, EventArgs e)  {      foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)      {          dataGridView1.Rows.RemoveAt(item.Index);      }  } 
like image 50
Navid Farhadi Avatar answered Sep 28 '22 08:09

Navid Farhadi


private void buttonRemove_Click(object sender, EventArgs e) {     foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)     {         if (oneCell.Selected)             dataGridView1.Rows.RemoveAt(oneCell.RowIndex);     } } 

Removes rows which indexes are in selected cells. So, select any cells, and their corresponding rows will be removed.

like image 28
Filip Avatar answered Sep 28 '22 07:09

Filip