gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:27:02 25 4
gpt4 key购买 nike

这是一个简单的问题,但由于我是 C# 的新手,所以我不确定如何解决这个问题。基本上,我有一个显示 MySQL 表中记录的数据 GridView 。我有一个删除按钮,通过单击它执行 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 行: enter image description here当我点击删除按钮时其他行被删除 enter image description here

最佳答案

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

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

关于c# - 试图从 datagridview 中删除选定的行,但它正在删除多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34355710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com