如何搜索中间有空格的字符串

时间:2017-12-03 20:03:53

标签: vb.net

我是VB的新手。所以当我运行我的程序并搜索名称。我想搜索中间的任何空格。例如,我想搜索" Brian Tracy"像那样

我对能够做到这一点的字符串函数感到很困惑。谢谢你的帮助

这是我正在处理的代码

Dim search As String = txtAuthorsName.Text


'Search Sql For Authors Data
Dim conn As New     
OleDb.OleDbConnection("Provider=Microsoft.ACE.OleDb.12.0;Data Source=" +
                                          Server.MapPath("~/Access/bookstore.accdb"))
conn.Open()

Dim sql As String = "SELECT AID, authorName, authorSex FROM Authors" 

Dim cmd As Object
If searchAuthor.SelectedValue.Equals("Name") Then
    If search.Length > 0 Then
       Dim keywords As String() = search.Split(" ")
       sql = "SELECT * FROM Authors where authorName like '%" & keywords(0) & "%'"
       For k As Integer = 1 To keywords.Length - 1
          sql += " or authorName Like '%" & keywords(k) & "%'"
       Next
    End If
    cmd = New OleDb.OleDbCommand(sql, conn)
    cmd.Parameters.AddWithValue("@authorName", "%" + txtAuthorsName.Text + "%")
Else
   sql += "WHERE authorSex LIKE @authorSex"
   cmd = New OleDb.OleDbCommand(sql, conn)
   cmd.Parameters.AddWithValue("@authorSex", "%" + txtAuthorSex.Text + "%")
End If

Dim dbread = cmd.ExecuteReader()
GridView2.DataSource = dbread
GridView2.DataBind()
dbread.Close()
conn.Close()

1 个答案:

答案 0 :(得分:0)

这是关于如何过滤/搜索数据的示例:

  Public Sub FilterData(valueToSearch As String)
    '
    Dim searchQuery As String = "SELECT * From Users WHERE CONCAT(fname, lname, age) like '%" & valueToSearch & "%'"

    Dim command As New SqlCommand(searchQuery, connection)
    Dim adapter As New SqlDataAdapter(command)
    Dim table As New DataTable()

    adapter.Fill(table)

    DataGridView1.DataSource = table

End Sub

Private Sub BTN_FILTER_Click(sender As Object, e As EventArgs) Handles BTN_FILTER.Click

    FilterData(TextBox1.Text)

进行必要的修改,希望它有效