It is a simple question, but since I am new to C#, I am not sure how to solve this. Basically, I have a datagridview that displays records from MySQL table. I have a delete button, which by clicking performs the sql query, which is working fine, and is also meant to then delete the selected row from datgridview. But what actually happening, is it deletes multiple rows even when only one row is selected. Here is the query:
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);
}
}
}
Screenshots: Row 6 should be deleted: Other Rows are deleted when I click Delete button
I think your problem is with your foreach
loop. You are looping through all your rows with dataGridView1.Rows
. Tr dataGridView1.SelectedRows
instead:
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
if (!row.IsNewRow) dataGridView1.Rows.Remove(row);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments