2017-07-25 60 views
-1

我創建了一個搜索按鈕來查詢我的MS Access數據庫並顯示結果,但每當我輸入ID並單擊搜索按鈕它什麼也不做。搜索按鈕沒有響應

其他所有工作,它從VB窗體複製數據並將其存儲在MS Access數據庫中,但搜索按鈕不查詢數據庫並檢索數據。

下面是我的搜索按鈕的代碼:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click 
    Dim found As Boolean 

    Try 
     cm = New OleDb.OleDbCommand 
     With cm 
      .Connection = cn 
      .CommandType = CommandType.Text 
      .CommandText = "SELECT* FROM tblInfo WHERE (ID = @ID & txtFind.Text = @ID)" 
      dr = .ExecuteReader 
     End With 
     While dr.Read() 
      found = True 
      txtFirst1.Text = dr("Pfirst").ToString 
      txtMid1.Text = dr("Pmiddle").ToString 
      txtLast1.Text = dr("Plast").ToString 
      txtAdd1.Text = dr("Paddress").ToString 
      txtPhone1.Text = dr("Pphone").ToString 
      txtContact1.Text = dr("Pcontact").ToString 

     End While 
     cn.Close() 
     Exit Sub 
     If found = False Then MsgBox("Patient ID not found!", MsgBoxStyle.Critical) 
     dr.Close() 

    Catch ex As Exception 

    End Try 

我怎樣才能解決這個問題?

+0

你將有一個明顯的錯誤信息,告訴你什麼是錯的,如果你吞嚥的werent例外。請閱讀[問]並參加[旅遊] – Plutonix

回答

0

問題是嘗試將txtFind.Text的值傳遞到命令中。

你想用parameters

With cm 
    .Connection = cn 
    .CommandType = CommandType.Text 
    .CommandText = "SELECT * FROM tblInfo WHERE ID = ?" 
    .Parameters.Add("@ID", OleDbType.[Type]).Value = txtFind.Text 
    dr = .ExecuteReader 
End With 

請注意,我用OleDbType.[Type]。您需要用您爲列ID指定的數據類型來替換它。

它也像你已經錯過了打開調用ExecuteReader()之前的連接:

cn.Open() 

我會考慮實施Using

有時你的代碼需要非託管資源,如文件句柄,COM包裝器或SQL連接。使用塊可以保證在您的代碼完成後處置一個或多個這樣的資源。這使它們可供其他代碼使用。

下面是一些示例代碼:

Using con As New OleDbConnection(connectionString), 
     cmd As New OleDbCommand("SELECT * FROM tblInfo WHERE ID = ?", con) 

    con.Open() 

    cmd.Parameters.Add("@ID", OleDbType.[Type]).Value = txtFind.Text 
    dr = cmd.ExecuteReader() 

    ... 

End Using