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.


Solution 1:

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);
     }
 }

Solution 2:

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.

Solution 3:

I have written the following code, please take a look:

foreach (DataGridViewRow row in dataGridView1.SelectedRows)
    if (!row.IsNewRow) dataGridView1.Rows.Remove(row);

using the Index of the selected row still could work; see if the code below will do the trick:

int selectedCount = dataGridView1.SelectedRows.Count;           
while (selectedCount > 0)
{
    if (!dataGridView1.SelectedRows[0].IsNewRow)
        dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
    selectedCount--;
}

I hope this helps, regards.