到目前为止,我已设法从按钮单击事件的datagrid视图中删除记录,但问题是数据库没有更改。
我使用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命令存在问题,但我无法想到另一种方式。有什么想法吗?
答案 0 :(得分:1)
您需要创建并提供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();
}
}
}
}
答案 1 :(得分:1)
尝试使用此方法从数据库中删除所选的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");
}
答案 2 :(得分:0)
想想我找到了答案。我已将datagrid值分配给字符串并在数据库查询中使用它。
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();
}
}
}