搜索datagrid查看完全关键字

时间:2015-10-04 04:33:25

标签: mysql vb.net datagrid

我想让搜索结果准确无误。 例如我输入" L"我的程序只显示任何带有字母" L"在其中,而不是显示第一个字母是" L"的结果。那怎么办呢?

这是我的代码:

***在搜索或在搜索框上输入之前,用户必须先选择一个单选按钮来搜索列中的数据,在我的程序中有3个单选按钮(ID,姓氏,名字)

 Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
        Dim DataTable As New DataTable
        Dim DataAdapter As New MySqlDataAdapter
        MySqlConn = New MySqlConnection
        MySqlConn = New MySqlConnection("server=localhost;user id=root;password=root;database=PatientManagementSystem;")
        MySqlConn.Open()
        'SEARCH ID
        If rdbtnID.Checked = True Then
            txtSearch.MaxLength = 9
            With cmd
                .Connection = MySqlConn
                .CommandText = "SELECT * FROM newpatient WHERE ID like '%" & txtSearch.Text & "%'"
            End With
            DataAdapter.SelectCommand = cmd
            DataTable.Clear()
            DataAdapter.Fill(DataTable)
            dgvRecords.DataSource = DataTable
            MySqlConn.Close()
            'SEARCH LASTNAME
        ElseIf rdbtnLastname.Checked = True Then
            txtSearch.MaxLength = 32767
            With cmd
                .Connection = MySqlConn
                .CommandText = "select * from newpatient where Lastname like '%" & txtSearch.Text & "%'"
            End With
            DataAdapter.SelectCommand = cmd
            DataTable.Clear()
            DataAdapter.Fill(DataTable)
            dgvRecords.DataSource = DataTable
            MySqlConn.Close()
            'SEARCH FIRSTNAME
        ElseIf rdbtnFirstname.Checked = True Then
            txtSearch.MaxLength = 32767
            With cmd
                .Connection = MySqlConn
                .CommandText = "SELECT * FROM newpatient WHERE Firstname like '%" & txtSearch.Text & "%'"
            End With
            DataAdapter.SelectCommand = cmd
            DataTable.Clear()
            DataAdapter.Fill(DataTable)
            dgvRecords.DataSource = DataTable
            MySqlConn.Close()

        End If

    End Sub

1 个答案:

答案 0 :(得分:1)

您需要从头开始删除%like符号。

更改

"SELECT * FROM newpatient WHERE ID like '%" & txtSearch.Text & "%'"

成:

"SELECT * FROM newpatient WHERE ID like '" & txtSearch.Text & "%'"

我还建议:(1)如果这是一个生产系统,使用参数化的sql;(2)如果你坚持使用sql连接,你需要转义txtSearch.Text中的任何单引号,用户输入2个单引号。否则sql语句将失败。