VB.NET中DataGridView按键筛选遇报错:需绑定BindingSource数据源
按键筛选产品信息时DataGridView绑定DataView报错的解决方法
问题代码
当前用于按键筛选产品信息的VB.NET代码如下:
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
错误信息
运行时抛出异常:
System.NotSupportedException: The DataSource property of the containing DataGridView control must be set to a BindingSource.
错误指向代码行:
DataGridView1.DataSource = dv
解决方法
错误提示明确要求DataGridView的DataSource必须是BindingSource类型,不能直接绑定DataView。同时原代码存在每次按键都重复填充数据表的性能问题,优化方案如下:
1. 初始化时仅填充一次数据表
将数据填充逻辑移到窗体的Load事件中,避免重复加载数据:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Me.Test_LaunchTableAdapter.Fill(Me.DataSet1.Test_Launch) Me.DataGridView1.Visible = True End Sub
2. 通过BindingSource包装DataView绑定
在KeyPress事件中,用BindingSource作为中间层绑定DataView:
Private Sub TextBox3_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox3.KeyPress Dim dv As New DataView(Me.DataSet1.Test_Launch) ' 设置筛选条件 dv.RowFilter = "convert([Code Article], 'System.String') like '%" & TextBox3.Text & "%'" ' 实例化BindingSource并绑定DataView Dim bs As New BindingSource() bs.DataSource = dv ' 将BindingSource赋值给DataGridView DataGridView1.DataSource = bs End Sub
3. 额外优化:规避筛选文本的特殊字符风险
直接拼接文本到筛选条件可能因特殊字符导致逻辑错误,建议转义处理:
' 转义单引号、%、_等特殊字符 Dim filterText As String = TextBox3.Text.Replace("'", "''").Replace("%", "[%]").Replace("_", "[_]") dv.RowFilter = $"convert([Code Article], 'System.String') like '%{filterText}%'"
内容的提问来源于stack exchange,提问作者Dilip Athreya
相关产品推荐
相关产品推荐

