user3994130
user3994130

Reputation: 1

Filter DataGridView rows in .Net

I currently have a DataGridView which populates from a csv. I made a filter text box and button, with the intention that it would reload the data given a string in the text box, and only populate the rows that contain that string. The issue I'm having, is that it will only populate the rows if I enter the entire string that is contained in the cell. For example: If I search "hamburger", it will only populate a row if a cell in that row reads exactly "hamburger", it will not populate a row that has a cell that reads "hamburger and fries". This is baffling me because I'm including ".contains" in the code. Any help will be much appreciated. Thanks.

Private Sub btnFilter_Click(sender As Object, e As EventArgs) Handles btnFilter.Click

    Dim strFilter As String = txtFilter.Text

    Dim TextFieldParser1 As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\CR2600\mc.csv")
        TextFieldParser1.Delimiters = New String() {","}

    While Not TextFieldParser1.EndOfData
        Dim Row1 As String() = TextFieldParser1.ReadFields()
        If DataGridView2.Columns.Count = 0 AndAlso Row1.Count > 0 Then
            Dim i As Integer

            For i = 0 To Row1.Count - 1
                DataGridView2.Columns.Add("Column" & i + 1, "Column" & i + 1)
            Next
        End If

        If Row1.Contains(strFilter) Then
            DataGridView2.Rows.Add(Row1)
        End If
    End While
End Sub

Upvotes: 0

Views: 1001

Answers (1)

Tobias Knauss
Tobias Knauss

Reputation: 3539

This is because Row1 in your code is an array. Contains on an array only checks for exact matches of the given value in any field of the array. If you want to check for parts, then you have to loop over the array (for) by yourself and call the Contains on each array element value, so you're doing a string comparison then.

Dim bFound as Bool
bFound = false
For i = 0 to Row1.Length
  If Row1(i).Contains(strFilter) Then bFound = true
Next
If bFound Then DataGridView2.Rows.Add(Row1)

Besides that I suggest

  If Row1(i).IndexOf(strFilter, PARAM) >= 0 Then bFound = true

where PARAM is the System.StringComparison type, that let's you choose whether to compare case-sensitive or not.

P.S.: sorry for any failures in the code. I haven't used VB in a while, I'm doing C++ and C#.

Upvotes: 1

Related Questions