2016-08-01 53 views
2

我有一個datagridview,我導入一個excel file.my excel列是名稱,ID,性別,年級,座位號。我要的是過濾所有datagridview中的列(多列過濾器),除了通過文本框的名稱和標識。即當我在文本框中輸入單個單詞時,我希望它在同一時間過濾性別,年級和座位號的列。 這裏是Excel中導入代碼到DataGridView ....如何在VB.NET中從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

你做了什麼來實現搜索功能? – ganesshkumar

+0

你可以使用datatable.Select('插入你的條件')來過濾多行 – Leprechaun

回答

1

您應該將數據表綁定到BindingSource的,你想補充的設計師,然後綁定,爲電網。然後可以通過設置BindingSource的Filter屬性來過濾數據。它基本上是一個SQL WHERE子句,因此,就像在SQL中一樣,可以使用AND和OR運算符組合多個條件,例如,

myBindingSource.Filter = String.Format("Column1 LIKE '%{0}%' OR Column2 LIKE '%{0}%'", myTextBox.Text) 

請注意,您只能使用LIKE作爲文本列,而不能使用數字或日期或其他任何內容。

+0

我怎樣才能做到這一點與使用綁定源? – addis

+0

我編輯了代碼並在'Filter'屬性中添加了一個缺少的引用。 – jmcilhinney

+0

你有什麼反對使用'BindingSource'?沒有理由不這樣做。如果您決定不使用其中一個,那麼您可以設置'DataTable'的'DefaultView.RowFilter'屬性,而不是'BindiongSource'的'Filter'屬性。 – jmcilhinney