2012-07-29 82 views
0

我正在創建一個程序,其中用戶可以在訪問數據庫中搜索項目並將結果顯示在列表視圖中。如何搜索訪問數據庫並在Listview VB6中顯示?

當我點擊搜索時,所有的項目都顯示出來,但是當我在文本框中輸入一個項目時,不顯示任何內容。

這是我的代碼

Private Sub cmdProdSearch_Click() 
Dim conn As ADODB.Connection 
Dim rs As ADODB.Recordset 
Dim list_item As ListItem 
Dim itm As ListItem 

db_file = db_file & "ProductsDatabase.mdb" 
Set conn = New ADODB.Connection 
conn.ConnectionString = _ 
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\VB and  Database\ProductsDatabase.mdb;Persist Security Info=False" & _ 
"Data Source=" & db_file & ";" & _ 
"Persist Security Info=False" 
conn.Open 
Set rs = conn.Execute("Select * from Export") 

ListView1.ListItems.Clear 

If InStr(1, rs!Product, txtProduct.Text, vbTextCompare) Then 
With ListView1 
.View = lvwReport 
.FullRowSelect = True 
Do While Not rs.EOF 
Set itm = .FindItem(txtProduct.Text, lvwText, , lvwPartial) 
Set list_item = .ListItems.Add(, , rs!Product) 
list_item.SubItems(1) = rs!barcode & "" 
list_item.SubItems(2) = rs!quantity & "" 
list_item.SubItems(3) = rs!Department 
rs.MoveNext 
Loop 
End With 
End If 
End Sub 

任何想法有什麼不好? 我沒有得到一個錯誤,只是沒有顯示。 謝謝

回答

0

您正在使用if條件和循環以錯誤的方式。您的if條件檢查當前記錄的產品字段是否與輸入的文本相同。如果是這樣,循環記錄並將其添加到列表視圖。

你可以做搜索有兩種方式:

一是在SQL中使用LIKE。例如,SELECT * FROM Export WHERE product LIKE 'a%'將返回產品字段以「a」開頭的記錄。 有關詳細信息:http://www.w3schools.com/sql/sql_like.asp

花葯的辦法是遍歷所有記錄逐一使用if條件(比如你現在有),檢查該字段是否包含搜索文本。如果你正在使用這個,那麼你必須對你現在的代碼進行修改,在if循環中移動if條件。所以,它就像在while循環中一樣,你將使用if條件來檢查匹配。

+0

謝謝。我剛剛擺脫了If語句,並改變了與您所建議的類似的查詢。似乎現在正在工作。感謝您的幫助:) – user1532055 2012-07-30 13:57:57

+0

請接受這個答案(通過點擊附近的Tick Mark)。這意味着,您已選擇我的帖子作爲解決方案。祝你好運 :) – 2012-07-30 15:20:10

相關問題