首页 文章

尝试从datagridview中删除所选行,但它正在删除多行

提问于
浏览
3

这是一个简单的问题,但由于我是C#的新手,我不知道如何解决这个问题 . 基本上,我有一个显示MySQL表记录的datagridview . 我有一个删除按钮,通过单击执行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);
                }
            }
        }

截图: Row 6 should be deleted:
enter image description here
Other Rows are deleted when I click Delete button
enter image description here

3 回答

  • 0

    我认为你的问题与你的 foreach 循环有关 . 您正在使用 dataGridView1.Rows 循环遍历所有行 . Tr dataGridView1.SelectedRows 代替:

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

    您可以使用:

    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);
    
    }
    
  • 2

    怎么样创建新命令,有点像...

    DELETE FROM YourTable WHERE product_id = ?

    之后,您可以获得所选项目索引的值:

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

    最后运行命令并将命令传递给你的product_id int . 我认为它应该没有问题...

相关问题