Dilum Jayawardhana Dilum Jayawardhana - 3 months ago 9
C# Question

How can I delete a row in a datagrid view and update the MySQL database on a delete button click event?

So far I have managed to delete the record from the datagrid view on a button click event, but the problem is that the database is not changing.

I'm using

datagrid_booktitles.Rows.RemoveAt(oneCell.RowIndex);
to remove the row from the datagrid and
cmd = new MySqlCommand("DELETE FROM
sarasavi_library
.
book_title
WHERE
book_number
= 'book_number';");
to remove it from the database.

Below is my full code for the delete button click event:

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

cmd = new MySqlCommand("DELETE FROM `sarasavi_library`.`book_title` WHERE `book_number`= 'book_number';");
}
}


Am I doing something wrong here? I have a feeling that there's a problem with my MySQL command, But I can't think of another way. Any ideas?

Answer

Think I found the answer for this. I have assigned the datagrid value to a string and used it in the database query.

foreach (DataGridViewCell oneCell in datagrid_booktitles.SelectedCells)
{
   if (oneCell.Selected == false) continue;

   string i = datagrid_booktitles.SelectedRows[0].Cells[1].Value.ToString();
   datagrid_booktitles.Rows.RemoveAt(oneCell.RowIndex);
   string query = "DELETE FROM `sarasavi_library`.`book_title` WHERE `book_number`='" + i +"'";

   using (var conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["Constring"].ToString()))
   {
      using (var cmd = new MySqlCommand(query, conn))
      {
         conn.Open();
         cmd.ExecuteNonQuery();
      }
    }
  }