从datagridview C#中删除数据库中的行

时间:2017-03-20 22:54:22

标签: c# datagridview

我正在尝试从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?

1 个答案:

答案 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();