我有一个datagridview,我导入一个excel文件。我的excel列是名称,id,性别,等级,座位号。我想要的是过滤datagridview中的所有列(多列过滤器),除了名称和id一个文本框。即,当我在文本框中键入单个单词时,我希望它同时过滤性别,等级和座位的列。 这里是excel导入代码到datagridview ....
Private Sub OpenFileDialog1_FileOk(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim filePath As String = OpenFileDialog1.FileName
Dim extension As String =
Path.GetExtension(filePath)
Dim header As String = If(rbHeaderYes.Checked, "YES", "NO")
Dim conStr As String, sheetName As String
conStr = String.Empty
Select Case extension
Case ".xls"
'Excel 97-03
conStr = String.Format(Excel03ConString, filePath, header)
Exit Select
Case ".xlsx"
'Excel 07
conStr = String.Format(Excel07ConString, filePath, header)
Exit Select
End Select
'Get the name of the First Sheet.
Using con As New OleDbConnection(conStr)
Using cmd As New OleDbCommand()
cmd.Connection = con
con.Open()
Dim dtExcelSchema As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
sheetName = dtExcelSchema.Rows(0)("TABLE_NAME").ToString()
con.Close()
End Using
End Using
'Read Data from the First Sheet.
Using con As New OleDbConnection(conStr)
Using cmd As New OleDbCommand()
Using oda As New OleDbDataAdapter()
Dim dt As New DataTable()
cmd.CommandText = (Convert.ToString("SELECT * From [") & sheetName) + "]"
cmd.Connection = con
con.Open()
oda.SelectCommand = cmd
oda.Fill(dt)
con.Close()
'Populate DataGridView.
DataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub
答案 0 :(得分:1)
您应该将DataTable绑定到BindingSource,然后将其添加到设计器中,然后将其绑定到网格。然后,您可以通过设置BindingSource的Filter属性来过滤数据。它基本上是一个SQL WHERE子句,因此,就像在SQL中一样,您可以使用AND和OR运算符来组合多个条件,例如。
myBindingSource.Filter = String.Format("Column1 LIKE '%{0}%' OR Column2 LIKE '%{0}%'", myTextBox.Text)
请注意,您只能将LIKE用于文本列,而不能使用数字或日期或其他任何内容。