2013-04-02 121 views
0

我正在使用VB 2010 Express訪問.mdb格式的數據庫。 我想查找包含特定字符串和數字的行,所以我寫了while循環。我使用If語句來確保循環不超過最大行(MaxRows)並拋出錯誤。它一直給出的結果是:「找不到記錄」,即使數據庫中存在字符串。我究竟做錯了什麼?visual basic:找到匹配的字符串

備註:inc用於增加行數。消息框是隻以查看變量值

代碼:在消息框中的變量值的

Dim lpn As String 
    Dim lpn2 As String 


    inc = 0 

    lpn = TextBox5.Text 

    lpn2 = ds.Tables("RegisteredCarsDataSet").Rows(inc).Item(7) 

    MsgBox(lpn & " " & lpn2 & " ") 

    While lpn <> lpn2 

     If inc <> MaxRows - 1 Then 
      inc = inc + 1 
      lpn2 = ds.Tables("RegisteredCarsDataSet").Rows(inc).Item(7) 

      MsgBox(lpn & " " & lpn2) 
     Else 
      MsgBox("No record found.") 
      Exit While 
     End If 
    End While 

    TextBox1.Text = ds.Tables("RegisteredCarsDataSet").Rows(inc).Item(1) 
    TextBox2.Text = ds.Tables("RegisteredCarsDataSet").Rows(inc).Item(2) 
    TextBox3.Text = ds.Tables("RegisteredCarsDataSet").Rows(inc).Item(3) 
    TextBox4.Text = ds.Tables("RegisteredCarsDataSet").Rows(inc).Item(4) 
    ComboBox1.Text = ds.Tables("RegisteredCarsDataSet").Rows(inc).Item(5) 
    ComboBox2.Text = ds.Tables("RegisteredCarsDataSet").Rows(inc).Item(6) 
    TextBox5.Text = ds.Tables("RegisteredCarsDataSet").Rows(inc).Item(7) 
+0

Offtopic,但你不認爲發出直接的sql命令就像「select * from mytable where myfield like'mystring''?或者至少發佈類似條件的記錄集上的查找命令? – Arvo

+0

我不熟悉sql,這是我第一次使用數據庫。我用我唯一的方式知道。但如果你知道更好的方法,請告訴我。 –

+0

如果我使用「select * from mytable where myfield like'mystring'」,我應該將結果保存到新數據集中,是否正確? –

回答

0

仔細檢查表明,尾隨空格被添加到字符串出於某種原因。 .trim()處理了這一點。根據Arvo的建議(謝謝阿沃),經過一番研究,我用「select * from my table where myfield'mystring''命令並將結果保存在一個新的數據集中。即使在這段代碼中,我也必須使用.Trim()函數。任何想法爲什麼添加了尾部空格(請注意,TextBox 5是從另一個變量填充的,而不是手動填充)?

con.Open() 
    dss.Clear() 
    Dim idn As String = TextBox5.Text 
    Dim MaxRows2 As Integer 
    idn = idn.Trim() 

    sql = "SELECT * FROM Details WHERE TagID Like '" & idn & "'" 
    MsgBox(sql) 
    das = New OleDb.OleDbDataAdapter(sql, con) ' assign table to data adapter 
    das.Fill(dss, "SearchResults") 

    MaxRows2 = dss.Tables("SearchResults").Rows.Count 
    MsgBox(MaxRows2) 
    con.Close() 

    If MaxRows2 <> 0 Then 
     TextBox1.Text = dss.Tables("SearchResults").Rows(0).Item(1) 
     TextBox2.Text = dss.Tables("SearchResults").Rows(0).Item(2) 
     TextBox3.Text = dss.Tables("SearchResults").Rows(0).Item(3) 
     TextBox4.Text = dss.Tables("SearchResults").Rows(0).Item(4) 
     ComboBox1.Text = dss.Tables("SearchResults").Rows(0).Item(5) 
     ComboBox2.Text = dss.Tables("SearchResults").Rows(0).Item(6) 
     TextBox5.Text = dss.Tables("SearchResults").Rows(0).Item(7) 

    ElseIf MaxRows2 = 0 Then 
     MsgBox("No entry found") 
    End If