我想在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
答案 0 :(得分: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