2017-10-17 166 views
1

我有一个datagridview我在其中添加一些列,第一列有复选框 当我尝试选择与复选框多行并删除它,它只即使当我选择多行时,也会每次删除一行。c# - 无法删除与sqlite数据库datagridview中的多行

我用填充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(); 

     } 

我使用的代码删除

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"); 
      } 

     } 
     } 
+0

是否会引发异常或者什么都没有发生? –

+0

如果您选择了多行并单击删除,多次弹出消息框? – MisterMystery

+0

也可以在删除方法中清除'dataGridView1'后在哪里填充? – MisterMystery

回答

0

的代码,我认为这个问题是dataGridView1.Rows.Clear(); foreach循环中。由于foreach循环在(DataGridViewRow item in dataGridView1.Rows)上迭代,所以在清除行之后,没有什么可以迭代了。

+0

我删除dataGridView1.Rows.Clear();现在消息弹出多次,我不能做一次吗? –

+0

您将不得不将if语句与foreach循环外部的消息框一起移动。 – MisterMystery

+0

也不要从数据库中填充数据表直到foreach循环完成。您想要删除所有选定的行,然后重新填充数据表。 – MisterMystery