我有一个文本框,我希望当我们在文本框中输入内容时,它会从Excel中搜索该数据。然后,来自excel的所选数据的所有记录都应出现在DataGridView中。 我的代码只能从excel获取所有记录。
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='c:\MECH_1.xlsx';Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("Table", "TestTable")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
DataGridView1.DataSource = DtSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
答案 0 :(得分:0)
您需要在查询中提及您的textbox
值,并使用Like
命令,如下所示。
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New
System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data
Source='c:\MECH_1.xlsx';Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from
[Sheet1$] where country like '%" & Trim(textbox1.Text) & "%' or Name like '%" & Trim(textbox1.Text) & "%'", MyConnection)
MyCommand.TableMappings.Add("Table", "TestTable")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
DataGridView1.DataSource = DtSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
注意:WHERE country LIKE'%或%'查找任何位置都有“或”的值 WHERE CustomerName LIKE'%a'查找以“a”结尾的任何值 WHERE CustomerName LIKE'a%'查找以“a”开头的任何值