简体   繁体   English

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

[英]Deleting a row in a database from datagridview C#

I'm trying to remove an entry from both the datagridview and the database. 我正在尝试从datagridview和数据库中删除一个条目。 I got it so it removes the row from the data grid view but it fails to delete it also from the database. 我知道了,所以它从数据网格视图中删除了该行,但是它也无法从数据库中删除它。 Here is my code I have in place: 这是我已有的代码:

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

I'm at a loss concerning this, any help would be appreciated. 我对此不知所措,任何帮助将不胜感激。

Thanks! 谢谢!

Update - Is there a way to grab the value of individual cells to pass to the mysql command? 更新-有没有办法获取单个单元格的值以传递给mysql命令? For instance, grabbing the id? 例如,获取ID?

Your values for i probably don't match the id fields in the member table. 你值i可能不匹配的id在田里member表。

You probably need to change this line: 您可能需要更改以下行:

cmd.CommandText = "DELETE FROM members WHERE id = " + i;

to

cmd.CommandText = "DELETE FROM members WHERE id = " + row.cells[id.Index].ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM