How to remove selected row from datagridview and database

The idea is that the row selected during deletion is deleted from the datagridview, the database, and then the datagridview is updated. I suppose this should be done with SQL, but how would you associate this sqlcommand of type text with deletion code with this particular line? The database consists of one separate table, and the binding to it is bound.

Delete button:

private void btnBookRecord_Click(object sender, EventArgs e) { if (this.BooksGrid.SelectedRows.Count > 0) { foreach (DataGridViewRow dgvrCurrent in BooksGrid.SelectedRows) { if (dgvrCurrent == BooksGrid.CurrentRow) { BooksGrid.CurrentCell = null; } // Delete row code here } } } 
+4
source share
3 answers

For some reason, the datagridview will not be updated, although I copied the update code from the add button, which works. But it deletes the record from the database.

 private void deleteRecord() { if (BooksGrid.SelectedRows.Count > 0) { int selectedIndex = BooksGrid.SelectedRows[0].Index; int rowID = int.Parse(BooksGrid[0, selectedIndex].Value.ToString()); string sql = "DELETE FROM Table1 WHERE RowID = @RowID"; SqlCommand deleteRecord = new SqlCommand(); deleteRecord.Connection = Booksconnection; deleteRecord.CommandType = CommandType.Text; deleteRecord.CommandText = sql; SqlParameter RowParameter = new SqlParameter(); RowParameter.ParameterName = "@RowID"; RowParameter.SqlDbType = SqlDbType.Int; RowParameter.IsNullable = false; RowParameter.Value = rowID; deleteRecord.Parameters.Add(RowParameter); deleteRecord.Connection.Open(); deleteRecord.ExecuteNonQuery(); deleteRecord.Connection.Close(); booksDataset1.GetChanges(); sqlDataAdapter1.Fill(booksDataset1.Videos); } } 
+6
source

If you allow only one selection in a DataGridView, you can do it.

Let's say that the first column in the DataGridView is the row identification seed in the database.

 if (BooksGrid.SelectedRows.Count > 0) { int selectedIndex = BooksGrid.SelectedRows[0].Index; // gets the RowID from the first column in the grid int rowID = int.Parse(BooksGrid[0, selectedIndex].Value.ToString()); string sql = "DELETE FROM Table1 WHERE RowID = @RowID"; // your code for deleting it from the database // then your code for refreshing the DataGridView } 
+3
source
 DataGridView datagridview1; datagridview1.Rows.remove(datagridview1.SelectedRows[0]); 
-2
source

Source: https://habr.com/ru/post/1346563/


All Articles