mardi 17 octobre 2017

c#- Can't delete multi rows in datagridview with sqlite database

I've a datagridview in which i add some columns to it , The first column has checkbox when i try to select multirows with checkbox and delete it , it only deletes one row each time even when i select multi rows .

The code i use for filling the datagridview

 SQLiteDataAdapter da = new SQLiteDataAdapter("Select * From Data", con);
        DataTable dt = new DataTable();
        da.Fill(dt);

        foreach (DataRow item in dt.Rows)
        {
            int n = dataGridView1.Rows.Add();
            dataGridView1.Rows[n].Cells[0].Value = "false";
            dataGridView1.Rows[n].Cells[1].Value = item["id"].ToString();
            dataGridView1.Rows[n].Cells[2].Value = item["car_num"].ToString();
            dataGridView1.Rows[n].Cells[3].Value = item["customer"].ToString();
            dataGridView1.Rows[n].Cells[4].Value = item["driver"].ToString();
            dataGridView1.Rows[n].Cells[5].Value = item["first"].ToString();
            dataGridView1.Rows[n].Cells[6].Value = item["second"].ToString();
            dataGridView1.Rows[n].Cells[7].Value = item["sum"].ToString();
            dataGridView1.Rows[n].Cells[8].Value = item["price"].ToString();
            dataGridView1.Rows[n].Cells[9].Value = item["date1"].ToString();
            dataGridView1.Rows[n].Cells[10].Value = item["date2"].ToString();
            dataGridView1.Rows[n].Cells[11].Value = item["city"].ToString();
            dataGridView1.Rows[n].Cells[12].Value = item["type"].ToString();

        }

The code i use for deleting

private void bDelete_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow item in dataGridView1.Rows)
        {

                if (bool.Parse(item.Cells[0].Value.ToString()))
            {
                if (MessageBox.Show("Are you sure you want to delete these data ? ", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                {
                    con.Open();
                SQLiteCommand cmd = new SQLiteCommand("Delete From Data Where id='"+item.Cells[1].Value.ToString()+"'", con);
                cmd.ExecuteNonQuery();
                con.Close();
                SQLiteDataAdapter da = new SQLiteDataAdapter("Select * From Data", con);
                DataTable dt = new DataTable();
                dataGridView1.Rows.Clear();

                da.Fill(dt);
                MessageBox.Show("Success");
            }

        }
        }




Aucun commentaire:

Enregistrer un commentaire