试图从 datagridview 中删除选定的行,但它正在删除多行

Trying to delete selected row from datagridview but it is deleting multiple rows

这是一个简单的问题,但由于我是 C# 的新手,所以我不确定如何解决这个问题。 基本上,我有一个显示来自 MySQL table 的记录的数据网格视图。我有一个删除按钮,通过单击它执行 sql 查询,它工作正常,并且还意味着从 datgridview 中删除选定的行。但实际发生的是,即使只选择了一行,它也会删除多行。 这是查询:

    private void delete_btn_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            string constring = @"server = localhost; user id = root; password = pass; persistsecurityinfo = false; database = mapping; allowuservariables = false";
            using (MySqlConnection con = new MySqlConnection(constring))
            {
                using (MySqlCommand cmd = new MySqlCommand("UPDATE deletion SET date_time = UTC_TIMESTAMP() where product_id =" + proid_txtbx.Text, con))
                {
                    cmd.Parameters.AddWithValue("@product_id", row.Cells["product_id"].Value);
                    cmd.Parameters.AddWithValue("@product_name", row.Cells["product_name"].Value);
                    cmd.Parameters.AddWithValue("@category_id", row.Cells["category_id"].Value);
                    cmd.Parameters.AddWithValue("@date_time", row.Cells["date_time"].Value);
                    con.Open();
                    cmd.ExecuteNonQuery();
                }
                foreach(DataGridViewRow item in this.dataGridView1.SelectedRows)
                {
                   dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
                }
            }
        }

截图: 应删除第 6 行: 当我点击删除按钮时其他行被删除

我认为您的问题出在 foreach 循环上。您正在使用 dataGridView1.Rows 遍历所有行。 Tr dataGridView1.SelectedRows 改为:

foreach (DataGridViewRow row in dataGridView1.SelectedRows)
    if (!row.IsNewRow) dataGridView1.Rows.Remove(row);

创建新命令怎么样,比如...

DELETE FROM YourTable WHERE product_id = ?

之后可以得到选中项索引的值:

int product_id = Convert.ToInt32(DataGridView1.SelectedRows[0].Cells[0].Value)

在命令的末尾 运行 并将您从命令中获得的 product_id int 传递给它。我认为它应该没有问题...

您可以使用:

private void delete_btn_Click(object sender, EventArgs e)
{
   //Works even when whole row is selected.
   int rowIndex = datagridview.CurrentCell.RowIndex;

   //You can also then easily get column names / values on that selected row
   string product_id = datagridview.Rows[rowIndex].Cells["Column Name Here"].Value.ToString();

   //Do additional logic

   //Remove from datagridview.
   datagridview.Rows.RemoveAt(rowIndex);

}