2014-09-04 167 views
0

我已經構建了您可以在下圖中看到的小應用程序。使用數據綁定從數據庫中刪除記錄

enter image description here

我現在工作的刪除按鈕,但我堅持。當我點擊它時,似乎沒有任何事情發生。有誰能告訴我我錯過了什麼嗎?點擊刪除按鈕時,我想完全刪除數據庫中的記錄。

Public Class Form1 
    Dim connection As New OleDb.OleDbConnection  
    Dim sql As String        
    Dim DataAdapter As OleDb.OleDbDataAdapter  
    Dim Datatable As New DataTable     
    Dim ProjectBindingSource As New BindingSource 
    Dim sql_delete As String 

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
     Try 
      connection.ConnectionString = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=Z:\Corporate Reporting\2014_15\Corporate\QuarterlyReporting.accdb" 

      connection.Open() 
      sql = "SELECT * FROM Projects_Application ORDER BY ProjectID" 
      DataAdapter = New OleDb.OleDbDataAdapter(sql, connection) 
      DataAdapter.Fill(Datatable) 

      ProjectBindingSource.DataSource = Datatable 

      With cmbSearch 
       .DisplayMember = "ProjectID" 
       .ValueMember = "ProjectID" 
       .DataSource = ProjectBindingSource 
      End With 

      NavigateRecords() 

      connection.Close() 
     Catch ex As Exception 
      MsgBox(ex.Message) 
     End Try 
    End Sub 

    Private Sub NavigateRecords() 
     txtProgammeID.DataBindings.Clear() 
     txtProgramme.DataBindings.Clear() 
     txtProjectName.DataBindings.Clear() 
     txtProgammeID.DataBindings.Add("Text", ProjectBindingSource, "ProgrammeID") 
     txtProgramme.DataBindings.Add("Text", ProjectBindingSource, "Programme") 
     txtProjectName.DataBindings.Add("Text", ProjectBindingSource, "ProjectName") 
    End Sub 

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click 
     Dim Project_To_Delete As String 
     Project_To_Delete = txtProjectID.Text 
     Dim Delete As New OleDb.OleDbCommand("DELETE FROM Projects_Application WHERE ProjectID = " & Project_To_Delete, connection) 

     Delete.Parameters.Add(Project_To_Delete, OleDb.OleDbType.Integer, 3, "ProjectID") 
     DataAdapter.DeleteCommand = Delete 

     DataAdapter.Update(Datatable) 
     ProjectBindingSource.EndEdit() 
     ProjectBindingSource.DataSource = Datatable 
    End Sub  
End Class 

回答

0

您應該使用一個參數創建一次delete命令:項目ID,而不是在sql字符串中使用實際的項目ID。

的命令應該是這樣的

Dim Delete As New OleDb.OleDbCommand("DELETE FROM Projects_Application WHERE ProjectID = ?", connection) 

,你應該添加參數一樣

Delete.Parameters.Add("ProjectID", OleDb.OleDbType.Integer, 3, "ProjectID") 

同時確保連接實際上是開放的,不是封閉/處置。


DataTable/DataAdapter背後的想法是,你配置DataAdapter的命令一次,一個DataTable內完成所有的工作,並在完成後,只需撥打UpdateDataAdapter需要是實際執行的SQL語句

所以要刪除記錄,只需刪除DataTable中的特定行,然後調用AcceptChanges,然後通過調用DataAdapter.Update(Datatable)來更新db。

+0

感謝您的參與。我之所以建立這樣的sql語句,是因爲要刪除的項目是文本框中的一個diplasyed,它可以根據您在組合框中選擇的內容進行更改。我不知道如何在ProjectID始終更改時創建sql。它有任何意義嗎? – Darius 2014-09-04 14:33:37