DataGridView使用bindingsouce通过Textbox过滤

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

我想在C#和SQLite中搜索数据网格视图,但我没有Datagridview的绑定源。我用以下代码填充Datagridview:

Private Sub TxtSearch_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TxtSearch.TextChanged

Dim bs As BindingSource = New BindingSource
AccountTransactionLedgerDetailsDataGridView.DataSource = bs
bs.Filter = String.Format("AccountName LIKE '%{0}%'", TxtSearch.Text)
AccountTransactionLedgerDetailsDataGridView.Refresh()  

End Sub

enter image description here

vb.net
1个回答
2
投票

每次要过滤时都不要创建新的BindingSource。将BindingSource添加到设计器中的表单,然后在第一次绑定时使用它,例如

myDataAdapter.Fill(myDataTable)
myBindingSource.DataSource = myDataTable
myDataGridView.DataSource = myBindingSource

那么你只需要一行来过滤:

myBindingSource.Filter = String.Format("AccountName LIKE '%{0}%'", TxtSearch.Text)

编辑:

我刚刚测试了这段代码(您也可以这样做)并且它完全符合预期,即完全符合您的要求:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim table As New DataTable

    table.Columns.Add("Rank", GetType(String))

    With table.Rows
        .Add("First")
        .Add("Second")
        .Add("Third")
        .Add("Fourth")
        .Add("Fifth")
        .Add("Sixth")
        .Add("Seventh")
        .Add("Eighth")
        .Add("Ninth")
        .Add("Tenth")
    End With

    BindingSource1.DataSource = table
    DataGridView1.DataSource = BindingSource1
End Sub

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    BindingSource1.Filter = $"Rank LIKE '%{TextBox1.Text}%'"
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.