使用TextBox搜索DataGridView

问题描述 投票:-1回答:1

我希望能够使用Textbox搜索我的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
vb.net ms-access
1个回答
1
投票

试试这个:

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

您目前正在使用的方式,只会使用最后一个过滤器,因为每次尝试“添加”过滤器时都会替换它。

我假设你的查询是OR,但只是改变ORAND,如果这是你需要的。

玩得开心!

© www.soinside.com 2019 - 2024. All rights reserved.