如何在C#中使用ms访问从数据网格视图中删除数据

时间:2018-07-16 11:24:22

标签: c# datagridview windows-forms-designer ms-access-2003

private void Delete_Click(object sender, EventArgs e)
{
    //i have used this query for delete button
    DataSet ds = new DataSet(); 
    OleDbDataAdapter ad = new OleDbDataAdapter();  
    OleDbConnection con = new 
    OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data 
    Source=C:\Users\HP\Desktop\sd.mdb");
    con.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data 
    Source=C:\Users\HP\Desktop\sd.mdb";
    con.Open();
    //this is the query i have used
    OleDbCommand cmd = new OleDbCommand("DELETE FROM car_model WHERE Description ='" + des+ "'", con);
    cmd.ExecuteNonQuery();
    MessageBox.Show("Data Deleted");
    con.Close();
}
//i have table named:car_model & attribute as Description

1 个答案:

答案 0 :(得分:0)

您的引号看起来不正确,但是我的眼睛不好看,无论如何,编译器会立即将其识别出来,所以我想是另外一回事了。

private void BtnDelete_Click(object sender, RoutedEventArgs e)
{
   DataRowView drv = (DataRowView)dataGridView1.SelectedItem;
   int id = drv.Row[0];
   if(drv != null)
   {
       delete(id);
   }
}

public void delete(int id)
{ 
   try 
   {
      con.Open();
      OleDbCommand comm = new OleDbCommand("Delete From Car_Model Where Description = @Des", con);
      comm.Parameters.AddWithValue("@Des", id);
      comm.ExecuteNonQuery();
   }
   catch(OleDbException ex)
   {
       MessageBox.Show("DataConnection not found!", ex);
   }
   finally
   {
       con.Close();
   }

此外,请使用'@'字符来防止SQL注入问题。我认为这不一定是MS Access的问题,但这是一个很好的习惯。

https://www.w3schools.com/sql/sql_injection.asp