Syed Ahmed Jamil
Syed Ahmed Jamil

Reputation: 2126

Correct way of filtering datagrid using datatables in C# WPF

I am creating a WPF application. There is a DataGrid displaying my items and search bar to filter the data. As you know we can't have specific rows from a Dataable to be referenced from another datatable. So the way I'm filtering right now is cloning my original database and adding the rows which matches search bar text to the cloned datatable. After that setting the datagrid's ItemsSource to the cloned datatable to show the filtered rows.

Now the problem is that when I edit my datagrid with filtered rows then obviously that cloned datatable is being modified not the original datatable. So how can I make those changes in the original datatable as well ?

I tried referencing rows from original datatable but that's no possible as one DataRow in memory can have only one container, the original datatable in this case.

EDIT

The answer was simple instead of using 2 DataTable use a DataView which is designed for this very purpose. See the modified code below.

My filter logic:

var filteredTable = dt.Clone();

foreach( DataRow row in dt.Rows)
{
    if(row[FilterCategory].ToString().StartsWith(txtb_search.Text))
    {
         filteredTable.Rows.Add(row.ItemArray);
    }
}

ItemsGrid.ItemsSource = filteredTable.DefaultView;

Upvotes: 0

Views: 2610

Answers (1)

Syed Ahmed Jamil
Syed Ahmed Jamil

Reputation: 2126

Here is how to do filtering the correct way using DataView. The filter string can have many forms depending on the requirement. sortColumn is filterColumn right now but can be any column to base sort on. Here is a quick tutorial to all this: http://www.csharp-examples.net/dataview-rowfilter/

 string filterColumn = dt.Columns[columnIndex].ToString();
 string filter = filterColumn + " LIKE '" + txtb_search.Text + "*'";

 DataView dv = new DataView(dt, filter, sortColumn , DataViewRowState.CurrentRows);
 ItemsGrid.ItemsSource = dv;

Upvotes: 3

Related Questions