我如何在数据网格视图中删除一行,并在删除按钮单击事件上更新MySQL数据库

本文关键字:删除 按钮 一行 单击 事件 数据库 MySQL 更新 数据网 数据 网格 | 更新日期: 2023-09-27 18:05:28

到目前为止,我已经设法从数据网格视图中删除了一个按钮单击事件的记录,但问题是数据库没有改变。

我使用datagrid_booktitles.Rows.RemoveAt(oneCell.RowIndex);从数据网格中删除行,cmd = new MySqlCommand("DELETE FROM sarasavi_library . book_title WHERE book_number = 'book_number';");从数据库中删除行。

下面是删除按钮单击事件的完整代码:

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

我在这里做错了什么吗?我感觉我的MySQL命令有问题,但我想不出其他方法。什么好主意吗?

我如何在数据网格视图中删除一行,并在删除按钮单击事件上更新MySQL数据库

尝试从数据库中删除选定的datagridview行。

SqlConnection con=new SqlConnection(@"Data Source=.'SqlExpress;Initial      Catalog=DatabaseName;Integrated Security=True"); 
 SqlCommand cmd = new SqlCommand();
if (dataGridView1.Rows.Count > 1 && dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 1)
 {
 delcmd.CommandText = "DELETE FROM table_Name WHERE Column_Name=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString() + "";
                con.Open();
                delcmd.Connection = con;
                delcmd.ExecuteNonQuery();
                con.Close();
                dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
                MessageBox.Show("Row has been Deleted");

            }

您需要创建并提供MySqlConnection的实例,以便在数据库上执行命令。

private void btn_delete_Click(object sender, EventArgs e)
{
    foreach (DataGridViewCell oneCell in datagrid_booktitles.SelectedCells)
    {
        if (oneCell.Selected == false) continue;
        datagrid_booktitles.Rows.RemoveAt(oneCell.RowIndex);
        string query = 
            "DELETE FROM `sarasavi_library`.`book_title` WHERE `book_number`='book_number'"
        using(var conn = new MySqlConnection("yourConnectionString"))
        {
            using(var command = new MySqlCommand(query, conn))
            {
                conn.Open();
                command.ExecuteNonQuery();
            }
        }
    }
}

我想我找到了答案。我已经将数据网格值分配给一个字符串,并在数据库查询中使用它。

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