Search Amazon:

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

Sign In
  User Id 
  Password 


Submit Your Own Code and Articles




About TheScarms
About TheScarms

Ask me your programming questions

I read every email and answer all I can.

User Feedback: Comments: 1 Items to Show:     

     
Id:  1 Posted:  6/16/2007 12:06:20 AM By:  HAIDT3
I have some problems with these code. When I type first few letter, it's good. But when I type some difference letters which is not exist in my datagrid, these code made some errors...
Please help me...
 
You must log in to post feedback.
Comment:    
 

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

Email this page


TheScarms AppSentinel lets you securely copy protect and create evaluation versions of your software

TheScarms(tm) AppSentinel lets you quickly and easily create evaluation versions of your software and stop unauthorized copying and unregistered use of your programs!

Get your free
trial copy today!


      The World's Number 1 Web Host

© Copyright 2008 TheScarms