使用TextBox搜索DataGridView

时间:2019-02-27 19:11:33

标签: vb.net ms-access

我希望能够使用文本框在Datagridview中进行搜索。下面的代码之前运行良好。但是目前,它仅搜索“类别”列下的项目,而它也应该搜索所有其他列。

Public Sub loaddata()
' This loads data into the datagridview
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\inventory1.accdb")
    Try
        conn.Open()
        Dim cmd = New OleDb.OleDbCommand
        With cmd
            .Connection = conn
            .CommandText = "SELECT product_cat as category, product_name as ProductName, product_desc as ProductDesc, cost_price as CostPrice, sales_price as SalesPrice FROM tblproducts"
        End With

        Dim das = New OleDb.OleDbDataAdapter
        das.SelectCommand = cmd
        Dim dt = New DataTable
        das.Fill(dt)
        DataGridView2.DataSource = dt
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        conn.Close()
    End Try
End Sub

Private Sub txtfilter_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtfilter.TextChanged
    Try
        loaddata()
        DataGridView2.DataSource.DefaultView.RowFilter = String.Format("[ProductName] LIKE '%{0}%'", txtfilter.Text)
        DataGridView2.DataSource.DefaultView.RowFilter = String.Format("[ProductDesc] LIKE '%{0}%'", txtfilter.Text)
        DataGridView2.DataSource.DefaultView.RowFilter = String.Format("[category] LIKE '%{0}%'", txtfilter.Text)
    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
    End Try
End Sub

1 个答案:

答案 0 :(得分:1)

尝试一下:

DataGridView2.DataSource.DefaultView.RowFilter = String.Format("[ProductName] LIKE '%{0}%' OR [ProductDesc] LIKE '%{0}%' OR [category] LIKE '%{0}%'", txtfilter.Text)

您当前使用的方式,将仅使用最后一个过滤器,因为每次尝试“添加”过滤器时都将其替换。

我假设您的查询是OR,但是如果您需要,只需将OR更改为AND

玩得开心!