I'm trying to create loop that will delete data from my database at the same times.
here's my code.
using (MySqlConnection mysqlCon = new MySqlConnection(connectionString))
{
foreach (DataGridViewRow dr in bunifuCustomDataGrid1.Rows)
{
int inventid = Convert.ToInt32(bunifuCustomDataGrid1.Rows[bunifuCustomDataGrid1.CurrentRow.Index].Cells[0].Value);
mysqlCon.Open();
MySqlCommand cmd = new MySqlCommand("DELETE FROM bookdb.book WHERE (BookID = @uid)", mysqlCon);
cmd.Parameters.AddWithValue("uid", inventid);
cmd.ExecuteNonQuery();
mysqlCon.Close();
GridFill();
}
}
MessageBox.Show("DOne");
I can delete multiple record, but its out if order and chaos. I hope someone can help me.
////////////////////////////////////////////////////////
I've tried some answers below. this is the code that almost work for me.
using (MySqlConnection mysqlCon = new MySqlConnection(connectionString))
{
mysqlCon.Open();
var tr = mysqlCon.BeginTransaction();
foreach (DataGridViewRow dr in bunifuCustomDataGrid1.Rows)
{
var cmd = new MySqlCommand("DELETE FROM bookdb.book WHERE (BookID = @uid)");
cmd.Connection = mysqlCon;
cmd.Transaction = tr;
cmd.Parameters.AddWithValue("@uid", dr.Cells["BookID"].Value ?? DBNull.Value);
cmd.ExecuteNonQuery();
}
tr.Commit();
mysqlCon.Close();
//////////////////////////
}
MessageBox.Show("DOne");
GridFill();
////
///
the problem is it deleted all rows.
Update()method. If you are manipulating UI elements its a red flag.bunifuCustomDataGrid1.Rows?GridFill();does what I think it does, it probably shouldn't be inside that loop.