Home > Net >  DataGridView live search data
DataGridView live search data

Time:10-04

I am trying to add a search function to a DataGridView in vb.net using this code

For i As Integer = 0 To ContactsList.RowCount - 1
    For j As Integer = 0 To ContactsList.ColumnCount - 1
        If ContactsList.Rows(i).Cells(j).Value.ToString.ToLower.Trim = ContactsListSearch.Text.ToLower.Trim Then
            MsgBox("Item found "   i.ToString)
            ContactsList.Rows(i).Visible = True
        Else
            ContactsList.Rows(i).Visible = False
        End If
    Next
Next

I'm seeing the MsgBox show when the value matches, but the rows are not showing, it just hides all rows

CodePudding user response:

I added 2 Exits in the IF statement when the value matches as it's searching each column as well, so it was causing them to be hidden as it loops columns too

For i As Integer = 0 To ContactsList.RowCount - 1
    For j As Integer = 0 To ContactsList.ColumnCount - 1
        If ContactsList.Rows(i).Cells(j).Value.ToString.ToLower.Trim = ContactsListSearch.Text.ToLower.Trim Then
            MsgBox("Item found "   i.ToString)
            ContactsList.Rows(i).Visible = True
        Else
            ContactsList.Rows(i).Visible = False
        End If
    Next
Next

CodePudding user response:

Another possible option is to load data into a DataTable, create a BindingSource, set the BindingSource DataSource property to the DataTable. Set the DataGridView DataSource property to the BindingSource.

The following example works against a column in the DataTable. If the user clears the TextBox the filter is removed while if there is text filter with trim.

Private Sub SearchButton_Click(sender As Object, e As EventArgs) _ 
    Handles SearchButton.Click

    If String.IsNullOrWhiteSpace(SearchTextBox.Text) Then
        bindingSource.Filter = ""
    Else
        Dim currentRowCount = bindingSource.Count
        bindingSource.Filter = $"TRIM(LastName) = '{SearchTextBox.Text}'"
        MessageBox.Show($"Before: {currentRowCount} Now: {bindingSource.Count}")
    End If

End Sub

Edit If the column name might be variable consider loading a ComboBox with column names then adjust code as follows.

bindingSource.Filter = $"TRIM({FilterComboBox.Text}) = '{SearchTextBox.Text}'"

In most cases working against a data source is better than working against cells values as per the above recommendation.

  • Related