I encountered a problem while I was trying to
change and refresh a contetnt of my DataGrid.
I applied a ObservableCollection<object> recordset; to my DataGrid in this way dgView.ItemsSource = recordset;
and everythig worked fine.
The records are displayed correctly. Scrolling, Inseriting, Updating, Deleting are working fine but when I tried to implement
Refresh (F5) arrived the first problem.
I tried to clear the recordset in this way recordset.Clear(); then I regenerated the content using the same procedure used
for the first time after the Window Loaded event occured.
The problem is, my columns are duplicated. The DataGrid didn't cleared my content but displayed another copy of my previous content.
For example, if I had 5 columns in a row now I have 10 columns in the row of the same name and type.
I looked at recordset collection and there is everything OK.
Is there a way to change a content of the Datagrid possibly programatically ?
In addition to refresh a content I am thinking to implement a sort of filtering records before displaying it in the grid.
I thought to make it in the same way like Refresh but I am not totally sure if it is the right way.
Every help or hint is appreciated.
Thanks a lot.
I finally found the solution to my problem !
Many thanks to Mr. Stephen Wrighton and his blog
where I found the idea to resolve my problem.
Before every reloading of the content we must execute the next algorithm:
1. unlink the Data and the View
-----> dgView.ItemsSource = null;
2. clear the data collection or the recordset
3. (this is optional) destroy the data collecition container
-----> recordset = null;
4. (and not the least important) CLEAR THE COLUMNS from the Datagrid !!!!! ------> dgView.Columns.Clear();
5. (optionaly) tell the DataGrid to refresh its Items and consequently the shown content ------> dgView.Items.Refresh();
I was having a similar issue with a DataGrid that was bound to an ObservableCollection in a ViewModel, this meant without writing loats of plumbing code I couldn't use the above solution. However after a bit of digging it appears that calling recordset.ClearItems();
(assuming recordset is the ObservableCollection) fixes the problem, and the datagrid automatically refreshes!
Hope this helps someone else who has had a similar problem.