0
votes

I have a datagrid on my application getting it's data from a database. Which is working through putting it in to a datatable and then showing it using dataGrid1.ItemsSource = DT.DefaultView.

I also have a textbox which is going to be used as a search box. Im wanting the search box to search through the datagrid and show the correct data. show not just higlight but actually make the data disappear or reappear based on the user input in to the search box.

I have search through multiple forums but non of the solutions I found worked on my application. So if anyone could give me a solution i would be very grateful.

EDIT, Sorted the problem

Private Sub txtSearchBox_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles txtSearchBox.TextChanged

    If txtSearchBox.Text = "" Then
        dataGrid1.ItemsSource = DT.DefaultView 'puts the data in to the datagrid
        DT.DefaultView.RowFilter = Nothing
    Else
        chosenFilter = txtSearchBox.Text

        'sets the datagrid filter
        DT.DefaultView.RowFilter = "TYPEID LIKE '%" & chosenFilter & "%'"
    End If

End Sub
3

3 Answers

2
votes

There are a number of options solving your issue.

1) Using Filter on a CollectionView

Create ListCollectionView in your code behind/ViewModel. Put you data items into the collectionsView and bind the DataGrid Itemssoure to it. Then pass a Filter Delegate to the CollectionView which filters the items depending on the TextInput. Attach a Handler to the Textbox TextChanged event in order to refresh/filter the CollectionView whenever the text is changed. This is also explained here:How do I filter items from a collection?

2) Use Jeff Wilcox AutocompleteBox and implement a custom SelectionAdapter

This is a bit trickier but imho more elegant. You need Jeff Wilcox AutoCompleteBox which is contained in the WPF Toolkit - February 2010 Release. You can download it from here: WPF Toolkit Feb 2010. Features of this very useful control are explained here: Using Using the AutoCompleteBox in the WPF Toolkit and here AutoCompleteBox control: The missing guide. How to implement a custom Selection Adapter is explained here:Page Up/ Page Down adapter

0
votes

Apply changes in your search box to ItemsSource of your grid. It is all that you need for this.

0
votes
Private Sub txtSearchBox_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles txtSearchBox.TextChanged

If txtSearchBox.Text = "" Then
    dataGrid1.ItemsSource = DT.DefaultView 'puts the data in to the datagrid
    DT.DefaultView.RowFilter = Nothing
Else
    chosenFilter = txtSearchBox.Text

    'sets the datagrid filter
    DT.DefaultView.RowFilter = "TYPEID LIKE '%" & chosenFilter & "%'"
End If

End Sub