2014-09-02 49 views
0

我能夠將csv文件的內容讀入DataGridView1,但我無法過濾來自textbox2的數據。我嘗試了一些我在網上找到的不同的東西,但到目前爲止沒有任何工作。這是我所:如何在不使用數據庫時過濾datagridview

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 
    Dim fName As String = "" 
    OpenFileDialog1.InitialDirectory = "C:\" 
    OpenFileDialog1.Filter = "CSV Files (*.csv)|*.csv" 
    OpenFileDialog1.FilterIndex = 2 
    OpenFileDialog1.RestoreDirectory = True 
    If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then 
     fName = OpenFileDialog1.FileName 
    End If 
    Me.TextBox1.Text = fName 
    GetData(fName, DataGridView1, True) 
End Sub 
Private Sub GetData(ByVal Path As String, ByRef DG As DataGridView, Optional ByVal NoHeader As Boolean = False) 
    Dim Fields() As String 
    Dim Start As Integer = 1 
    If NoHeader Then Start = 0 
    If Not File.Exists(Path) Then 
     Return 
    End If 
    Dim Lines() As String = File.ReadAllLines(Path) 
    Lines(0) = Lines(0).Replace(Chr(34), "") 
    Fields = Lines(0).Split(",") 
    If NoHeader Then 
     For I = 1 To Fields.Count - 1 
      Fields(I) = Str(I) 
     Next 
    End If 
    For Each Header As String In Fields 
     DG.Columns.Add(Header, Header) 
    Next 
    For I = Start To Lines.Count - 1 
     Lines(I) = Lines(I).Replace(Chr(34), "") 
     Fields = Lines(I).Split(",") 
     DG.Rows.Add(Fields) 
    Next 

End Sub 

我只是希望能夠過濾通過鍵入TextBox2中說點什麼列5(以csv文件沒有列標題)。任何幫助將不勝感激。謝謝

回答

0

不要將值添加到DGV,而是使用DataTable然後只是對此進行查詢。例子認爲你有一個組合框用於某些過濾器選擇 - 它們是根據你的需要得到它的其他方法。這種方法需要你有標題。

Private dt As New DataTable 

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click 
Dim fName As String = "" 
OpenFileDialog1.InitialDirectory = "C:\" 
OpenFileDialog1.Filter = "CSV Files (*.csv)|*.csv" 
OpenFileDialog1.FilterIndex = 2 
OpenFileDialog1.RestoreDirectory = True 
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then 
    fName = OpenFileDialog1.FileName 
End If 
Me.TextBox1.Text = fName 
LoadData(fName) 
FilterData(combobox1.Text, "some column name") 
End Sub 

Private Sub LoadData(ByVal Path As String) 
Dim Fields() As String 
Dim Start As Integer = 1 
If NoHeader Then Start = 0 
If Not File.Exists(Path) Then 
    Return 
End If 
Dim Lines() As String = File.ReadAllLines(Path) 
Lines(0) = Lines(0).Replace(Chr(34), "") 
Fields = Lines(0).Split(",") 
For I = 1 To Fields.Count - 1 
    Fields(I) = Str(I) 
Next 
For Each Header As String In Fields 
    dt.Columns.Add(Header, Header) 
Next 
For I = Start To Lines.Count - 1 
    Lines(I) = Lines(I).Replace(Chr(34), "") 
    Fields = Lines(I).Split(",") 
    dt.Rows.Add(Fields) 
Next 
End Sub 

Private Sub FilterData(filter As String, columnName as string) 
    Dim query = From dr As DataRow In dt.Rows Where dr(columnName).ToString = filter 
    DGV.DataSource = query 
End Sub 
相關問題