Search by LIKE not working in database vb.net

126 views Asked by At

For some reason the like is not working, for example is the name where Jason and I search for 'Ja', 'jason' should show up it does not. Is my code faulty? This is in a local database, maybe that helps?

 Private Sub BTN_Search_Click(sender As Object, e As EventArgs) Handles BTN_Search.Click
    'If txtbox is blank then show all records, else do the search by first name.
    If TBX_Search.Text = "" Then
        DoctorsDataGridView.DataSource = Me.RecordsDataSet.Doctors.Select("FirstName LIKE'" & "%" & "'")
    Else
        DoctorsDataGridView.DataSource = Me.RecordsDataSet.Doctors.Select("FirstName LIKE'" & TBX_Search.Text & "'")
    End If
 End Sub
3

There are 3 answers

0
Roy van der Velde On BEST ANSWER
 Private Sub BTN_Search_Click(sender As Object, e As EventArgs) Handles BTN_Search.Click
      'If txtbox is blank then show all records, else do the search by first name.
      If TBX_Search.Text = "" Then
           DoctorsDataGridView.DataSource = Me.RecordsDataSet.Doctors.Select("FirstName LIKE '%'")
      Else
           DoctorsDataGridView.DataSource = Me.RecordsDataSet.Doctors.Select("FirstName LIKE '%" & TBX_Search.Text & "%'")
      End If
 End Sub

In your code you tell the database to fetch articles matching Ja instead of looking for Ja% (and anything behind it)

  • Add the % before your searchstring to allow results with anything in front of the Ja
  • Add the % after your searchstring to allow results with anything after the Ja
  • Add them both before and after the searchstring to match any result with the term Ja in it
2
Paul Abbott On

% indicates the partial or missing part(s), you still need it (for your case) at the end.

DoctorsDataGridView.DataSource = Me.RecordsDataSet.Doctors.Select("FirstName LIKE'" & TBX_Search.Text & "%'")

Also, google "SQL injection", the above code is asking for trouble.

0
Noel On

It looks like you need the wildcard on the Else logic:

DoctorsDataGridView.DataSource = Me.RecordsDataSet.Doctors.Select("FirstName LIKE'" & TBX_Search.Text & "%'")

This is the logic for "starts with" text.