Search code examples
c#databasems-accessdatagridviewdelete-row

Delete Row from DataGridView and Access Database, it`s delete my all database


In dataGrid delete the selected row, but my database is erased.

private void button2_Click(object sender, EventArgs e)
    {
                foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
                {
                    dataGridView1.Rows.RemoveAt(item.Index);
                }

                con.Open();
                ad.SelectCommand = new OleDbCommand("delete * from Animale", con);
                ds.Clear();
                ad.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];

                ad.SelectCommand.ExecuteNonQuery();
                con.Close();
    }

Solution

  • If you still want to do this using a query then you will need a WHERE clause in your delete statement.

    To put you on the right path

                foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
                {
                    dataGridView1.Rows.RemoveAt(item.Index);
    
                    con.Open();
                    ad.SelectCommand = new OleDbCommand("delete * from Animale where id = " + item.id.ToString, con);
                }
    

    but you should really use parameters