AlexKK
AlexKK

Reputation: 57

How to search multiple values in one textbox and shown in DataGridView vb.net

Is there a way to search/filter multiple values in one textbox? I am searching for two or more different words, phrases in column OPIS.

enter image description here

Example: Searching for sveder and then din 374 and then TiN and the result will be all items that have this description

I have this code but it is problem when search is not exactly the same as description. Database is imported from Access.

    Public Class Form1
    Private Sub PodatkiBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
        Me.Validate()
        Me.PodatkiBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.PodatkiDataSet)

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'PodatkiDataSet.Podatki' table. You can move, or remove it, as needed.
        Me.PodatkiTableAdapter.Fill(Me.PodatkiDataSet.Podatki)

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        PodatkiBindingSource.Filter = "(Convert(KODA, 'System.String') LIKE '" & TextBox1.Text & "%')" &
                     "OR (OPIS LIKE '%" & TextBox1.Text & "%')"

    End Sub
End Class

Upvotes: 1

Views: 1195

Answers (1)

dr.null
dr.null

Reputation: 4695

Yes there is. For example:

  • In the search TextBox, separate the search words by a delimiter like comma , to split the string and create an array of them.
  • Put the target columns in another array.
  • Use nested loop to form the filter in a StringBuilder object.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If TextBox1.Text.Trim().Length = 0 Then
        PodatkiBindingSource.Filter = Nothing
    Else
        Dim sb = New System.Text.StringBuilder()
        Dim cols = {"KODA", "OPIS"}
        Dim words = TextBox1.Text.Split({","}, StringSplitOptions.RemoveEmptyEntries).
            Where(Function(x) x.Trim().Length > 0)

        For i = 0 To cols.Count - 1
            For j = 0 To words.Count - 1
                sb.Append($"{cols(i).Trim()} LIKE '%{words(j).Trim()}%'")
                If j <> words.Count - 1 Then sb.Append(" OR ")
            Next
            If i <> cols.Count - 1 Then sb.Append(" OR ")
        Next
        PodatkiBindingSource.Filter = sb.ToString()
    End If
End Sub

Upvotes: 2

Related Questions