我正在尝试从datagridview和数据库中删除一个条目。我得到了它,所以它从数据网格视图中删除了行,但它也无法从数据库中删除它。这是我的代码:
private void listBtn_Click(object sender, EventArgs e)
{
MySqlDataAdapter mysqldatadapter = new MySqlDataAdapter("select id, username from members ORDER BY id", new MySqlConnection(conn.connectionString));
mysqldatadapter.Fill(ds);
dataGridView.DataSource = ds.Tables[0];
listBtn.Enabled = false;
}
private void btnDelete_Click(object sender, EventArgs e)
{
using (MySqlConnection dbConn = new MySqlConnection(conn.connectionString))
{
dbConn.Open();
for (int i = 0; i < dataGridView.Rows.Count; i++)
{
DataGridViewRow row = dataGridView.Rows[i];
if (row.Selected == true)
{
dataGridView.Rows.RemoveAt(i);
MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "DELETE FROM members WHERE id = " + i;
try
{
cmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}
dbConn.Close();
}
}
我对此感到茫然,任何帮助都会受到赞赏。
谢谢!
更新 - 有没有办法获取单个单元格的值以传递给mysql命令?例如,抓住id?
答案 0 :(得分:0)
i
的值可能与id
表中的member
字段不匹配。
您可能需要更改此行:
cmd.CommandText = "DELETE FROM members WHERE id = " + i;
到
cmd.CommandText = "DELETE FROM members WHERE id = " + row.cells[id.Index].ToString();