2010-03-26 43 views
0

我有MS Access数据库,datagridview显示项目,两个复选框列表示数据库中的是/否列和刷新/ del按钮。为什么会收到并发违规错误?

当我尝试删除其复选框未被修改的行时,行删除就好了,当我修改复选框的值时,按下刷新按钮,然后删除,行也会删除。

但是,当我尝试在修改其复选框值后立即删除行时,出现了并发冲突异常错误。

当复选框的值更改代码:

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) 
    { 

     if (dataGridView1.Columns[e.ColumnIndex].Name == "sales") 
     { 

      DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells["sales"]; 
      bool _pSale = (Boolean)checkCell.Value; 

      string connstring = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}", Path.Combine(Directory.GetCurrentDirectory(), "MyDatabase01.accdb")); 
      OleDbConnection conn = new OleDbConnection(connstring); 
      conn.Open(); 

      string sqlqry = "UPDATE Items SET pSale = " + _pSale + " WHERE p_Name = '" + this._pName + "'"; 
      OleDbCommand upd = new OleDbCommand(sqlqry, conn); 
      upd.ExecuteNonQuery(); 
      conn.Close(); 
      //dataGridView1.Invalidate(); 

     } 
} 

刷新按钮代码:

public void Refreshdgv() 
     { 
      this.categoriesItemsBindingSource.EndEdit(); 
      this.itemsTableAdapter.Fill(myDatabase01DataSet.Items); 
      this.dataGridView1.Refresh(); 
     } 

删除按钮代码:

private void delBtn_Click(object sender, EventArgs e) 
    { 
      try 
      { 

       int cnt = dataGridView1.SelectedRows.Count; 
       for (int i = 0; i < cnt; i++) 
       { 
        if (this.dataGridView1.SelectedRows.Count > 0) 
        { 
         this.dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index); 
        } 
       } 


       this.Validate(); 
       this.categoriesItemsBindingSource.EndEdit(); 
       this.itemsTableAdapter.Update(this.myDatabase01DataSet.Items); 
       this.myDatabase01DataSet.AcceptChanges(); 

      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.ToString()); 
      } 
    } 

要解决这个问题,我可以叫Refreshdgv()方法代替dataGridView1.Invalidate()。但我不想为每个复选框点击dgv刷新!

回答

1

DataSet的delete命令可能检查原始值。由于您在CellValueChanged事件中手动更新数据库,因此数据库中的值与您的DataSet中的原始值不匹配。如果您修改CellValueChanged事件以在您的DataSet中使用update命令,则当您调用Delete时,值应与匹配。

或者,您可以将您的删除命令更改为使用不太专有的where子句(例如,WHERE KeySegment0 = @keySegment0 AND KeySegment1 = @keySegment1 ...)。

+0

谢谢,我不应该手动更新我的数据库,这是问题。我使用tableadapter update命令替换了dgv单元格更改事件中的更新代码,它起作用。 – DanSogaard 2010-03-26 15:47:34

0

尝试验证数据,然后更新它。在此之后,清除你的数据集并填充它,这样它会刷新你所做的每一个更改的数据网格。