Filter DataGrid rows as the user types

Suppose you show a large number of rows in a WinForms DataGrid and you want to limit the rows displayed as the user types a column's value into a textbox. You can do this by filtering the bound datatable's defaultview.

Retrieve data from the database:

    Imports System.Data.OleDb

    Dim strSQL As String = "Select * From Customers"
    Dim Connection As New OleDbConnection(strConnection)
    Dim DA As New OleDbDataAdapter(strSQL, Connection)
    Dim DS As New DataSet

    DA.Fill(DS, "Customers")

Bind the DataSet to the DataGrid using the DataGrid's DataSource property.

    '
    ' Bind the DataGrid to the DataSet. Expand and navigate to first row.
    '
    If DS.Tables("Customers").Rows.Count > 0 Then
        With DataGrid
           .DataSource = DS.Tables("Customers")
           .Expand(-1)
           .NavigateTo(0, "Customers")
        End With
    End If

Filter the datagrid in the textbox's TextChanged event.

    Private Sub txtText1_TextChanged(ByVal sender As System.Object, _
                    ByVal e As System.EventArgs) Handles txtText1.TextChanged

        Dim aFilter As String
        Dim aRows As Integer
        '
        ' Create the filter string.
        '
        If txtText1.Text.Trim = "" Then
            aFilter = ""
        Else
            aFilter = "Customer_Name Like '" & txtText1.Text & "*'"
        End If
        '
        ' Apply the filter.
        '
        DS.Tables("Customers").DefaultView.RowFilter = aFilter
        aRows = DS.Tables("Customers").DefaultView.Count

        If aRows = 0 Then
            lblStatus.Text = "No data found."
        Else
            lblStatus.Text = "Rows: " & aRows.ToString
        End If

    End Sub




About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2024 TheScarms
Goto top of page