Search code examples
vb.netms-accessselectsql-like

VB.Net Select-Like query in MS Access not working


I need to show the data from the column 'Purchaser' starting with the text entered in the textbox 'Purchaser' on the form. I am using MS Access 2003 database. For this I am using the following...

            Dim query = "SELECT * FROM Details WHERE [Purchaser] LIKE '" & Purchaser.Text & "*'"
            Dim dc = New OleDbCommand(query, cn)
            Dim rows = dc.ExecuteNonQuery
            cn.Close()

            If rows = 0 Then
                'Show a form for new entry
            Else

                Dim oleadap = New OleDbDataAdapter(query, cn)
                Dim dset As DataSet = Nothing
                oleadap.Fill(dset, "Details")

                For i = 0 To rows
                    Dim purName = dset.Tables("Details").Rows(i).Item("Purchaser").ToString
                    Dim purAddr = dset.Tables("Details").Rows(i).Item("Address").ToString

                    'Populate a list

                Next

            End If

The variable 'rows' always turns out to be zero even if I check for a Purchaser starting with, say A, in the database.


Solution

  • That should be:

    Dim query = "SELECT * FROM Details WHERE [Purchaser] LIKE '" _
              & Purchaser.Text & "%'"
    

    In MS Access, the wild card is asterisk (*), outside of it, the wildcard is percent (%)

    In addition, you have ExecuteNonQuery, but that is not true. You are executing a query, here are a few notes for testing.

    Dim query = "SELECT * FROM Details WHERE [Purchaser] LIKE '" _
              & Purchaser.Text & "%'"
    Dim dc = New OleDbCommand(query, cn)
    Dim rows As OleDb.OleDbDataReader
    rows = dc.ExecuteReader
    
    If rows.HasRows Then
        Do While rows.Read()
            Console.WriteLine(rows("Purchaser"))
        Loop
    End If
    Console.ReadLine()