EDIT: I am using VS2008, .NET 3.5
I have a DataTable, which is populated in a DataView and passed into a CollectionView.
DataTable newLeadTable = new DataTable();
myConnection.Open();
dbAdpater.Fill(newLeadTable);
this.LeadDataView = new DataView(newLeadTable);
this.LeadsCollectionView =
CollectionViewSource.GetDefaultView(this.LeadDataView);
Then the DataGrid that use to display the data is binding to this.LeadsCollectionView
After the user enter the filter text in the View, the ViewModel will execute this method to set the filter string on the DataView:
private void SetLeadListFilter(string LeadFilterStr)
{
this.LeadDataView.RowFilter = filterString;
}
It works fine, I can see the DataGrid shows proper filtered DataRow.
But then I want to give some UI Experience, add a busy indicator.
So I put the above code into a Thread:
this.IsBusy = true;
Thread filterDataThread= new Thread(new ThreadStart(() =>
{
this.LeadDataView.RowFilter = filterString;
this.IsBusy = false;
}));
filterDataThread.Start();
Now is strange, I can see the code was ran, filter being setted. But the DataGrid doesn’t filter out the rows!
So now I modify the method, reassign the DataView into the CollectionView again:
this.IsBusy = true;
Thread filterDataThread= new Thread(new ThreadStart(() =>
{
this.LeadDataView.RowFilter = filterString;
this.LeadsCollectionView = CollectionViewSource.GetDefaultView(this.LeadDataView); //Added this
this.IsBusy = false;
}));
filterDataThread.Start();
Now it working! The data is being filter properly on the DataGrid!
So why is this happen when I use threading? Is this the proper way to use DataFilter in Threading?
Can’t say for sure, but, as I’ve understand, you use
to get the Datasource for your DataGrid. Answer is based on this assumption.
So if you will cal this method outside the
filterDataThread, like this:then the code with
GetDefaultViewwill probably run before your Thread work – there would be a race betweenMainThreadandfilterDataThread, andMainThreadwins, and yourDataGriddoesn’t filter the data.But if you will use the code you’ve provided:
the filtering will start in right time.
So answer is:
Yes, you are doing the filtering right. But you should add code to handle errors while performing operations in background thread so your application wouldn’t be
Busyforever.Also, you should check the safe access to the
filterString– if you’ll start two or more threads for filtering, there would be another race with unpredictable results.