Excel数据导入DataGrid及基于TextBox的名称模糊筛选需求
实现DataGrid中NAME列的模糊筛选功能
现有Excel导入代码
你当前用于将Excel数据导入DataGrid的VB.NET代码如下:
Dim FileLoc As String = TxtFileLoc.Text Dim ConStr As String '= String.Empty If FileLoc.EndsWith(".xls") Then ConStr = String.Format("Provider=Microsoft.Jet.Oledb.4.0;" & "Data Source={0};Extended Properties='Excel 8.0;HDR=yes'", FileLoc) Else ConStr = String.Format("Provider=Microsoft.Ace.Oledb.12.0;" & "Data Source={0};Extended Properties='Excel 8.0;HDR=yes'", FileLoc) End If Dim Cmd As New OleDbDataAdapter("Select * from [" & ComboSheets.Text & "" & "]", ConStr) Cmd.TableMappings.Add("Table", "Table") Dim dt As New DataSet Cmd.Fill(dt) ExlDisp.DataSource = dt.Tables(0)
筛选功能实现步骤
要实现通过TxtFilterName文本框筛选NAME列包含指定内容的功能,可以通过DataView的RowFilter实现客户端筛选,无需重新读取Excel文件,步骤如下:
声明类级别的DataTable变量
在窗体类的顶部添加变量,保存导入的原始数据,方便后续筛选时访问:Private originalDataTable As DataTable ' 保存原始Excel数据修改导入代码,绑定DataView
调整原导入代码,将原始数据表赋值给类变量,并绑定DataView到DataGrid(而非直接绑定DataTable):Dim FileLoc As String = TxtFileLoc.Text Dim ConStr As String If FileLoc.EndsWith(".xls") Then ConStr = String.Format("Provider=Microsoft.Jet.Oledb.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=yes'", FileLoc) Else ConStr = String.Format("Provider=Microsoft.Ace.Oledb.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=yes'", FileLoc) End If ' 修正SQL语句的字符串拼接冗余问题 Dim Cmd As New OleDbDataAdapter($"Select * from [{ComboSheets.Text}]", ConStr) Cmd.TableMappings.Add("Table", "Table") Dim ds As New DataSet Cmd.Fill(ds) originalDataTable = ds.Tables(0) ' 绑定DataView,支持后续筛选 ExlDisp.DataSource = originalDataTable.DefaultView添加文本框的TextChanged事件处理
给TxtFilterName文本框添加TextChanged事件,实时根据输入内容更新筛选条件:Private Sub TxtFilterName_TextChanged(sender As Object, e As EventArgs) Handles TxtFilterName.TextChanged If originalDataTable IsNot Nothing Then Dim filterInput = TxtFilterName.Text.Trim() If String.IsNullOrEmpty(filterInput) Then ' 清空筛选,显示所有数据 originalDataTable.DefaultView.RowFilter = String.Empty Else ' 使用LIKE模糊匹配,%表示任意字符 originalDataTable.DefaultView.RowFilter = $"NAME LIKE '%{filterInput}%'" ' 若需要不区分大小写,可添加COLLATE子句: ' originalDataTable.DefaultView.RowFilter = $"NAME LIKE '%{filterInput}%' COLLATE SQL_Latin1_General_CP1_CI_AS" End If End If End Sub
效果说明
当你在TxtFilterName中输入"ANTONY"时,DataGrid会自动筛选并显示NAME列包含该字符串的行(即示例中的前两行数据);清空输入框则恢复显示所有数据。
内容的提问来源于stack exchange,提问作者Rajesh
相关产品推荐
相关产品推荐

