如何在 vb.net 中按键时在 datagridview 中进行过滤

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

您好,我需要在按键时过滤产品。我有以下代码,但它不起作用,任何人都可以建议如何操作。

Private Sub TextBox3_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox3.KeyPress
        Me.Test_LaunchTableAdapter.Fill(Me.DataSet1.Test_Launch)
        Me.DataGridView1.Visible = True
        Dim dv As DataView
        dv = New DataView(Me.DataSet1.Test_Launch, "(convert([Code Article], 'System.String') like '%" & TextBox3.Text & "%')", Nothing, DataViewRowState.CurrentRows)
        DataGridView1.DataSource = dv
    End Sub

But Iam getting this error
System.NotSupportedException: 'The DataSource property of the containing DataGridView control must be set to a BindingSource.(DataGridView1.DataSource = dv  in this line getting error)
vb.net filter datagridview
1个回答
0
投票

你的代码太疯狂了。每次用户按下一个键时,您都会查询数据库并获取已有的相同数据,然后在本地进行过滤。不要那样做。查询数据库一次并填充您的

DataTable
,将其绑定到
BindingSource
并将其绑定到您的
DataGridView
。然后,您应该在
Filter
BindingSource
事件上设置
TextChanged
TextBox
属性:

myBindingSource.Filter = $"[Code Article] LIKE '%{TextBox3.Text}%'"

更好的是,在

Timer
事件上重新启动
TextChanged
,然后在该
Filter
Tick
上设置
Timer
。这样,当用户连续键入多个字符时,您就不会一遍又一遍地进行过滤。您可以尝试使用
Interval
,这样用户在停止输入后不必等待太长时间即可看到过滤后的数据,但足够长的时间可以让他们可以输入多个字符,而不会在每个字符后进行过滤。 300 毫秒左右是一个不错的起点。我将把它留给你作为练习。请注意,您将在
Stop
事件中的
Start
上调用
Timer
TextChanged
,然后在
Stop
事件中调用
Tick

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