Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datagrid column Sorting generating error

I have a datagrid column whose column values are databound. I have used DataGridTemplateColumn and i need to use sorting in this column.

my:DataGridTemplateColumn SortMemberPath="FileName" Header="Name" IsReadOnly="True" MinWidth="150"

It works and sorts the data but when I edit the data after sorting, I need to re-generate the data in the column.

FileListingGrid.ItemsSource = listFiles1;

But this generates "'Sorting' is not allowed during an AddNew or EditItem transaction. "

It works fine when column data is not sorted but whenever i sort the data and have to re-generate the column data, it throws the following error.

like image 747
user456064 Avatar asked Oct 01 '10 10:10

user456064


2 Answers

There are two ways to resolve this issue

1) CommitNew() and CommitEdit() before custom sort

private void DataGrid_ParametersList_Sorting(object sender, DataGridSortingEventArgs e)
{
DataGridColumn column = e.Column;

//prevent the built-in sort from sorting
e.Handled = true;

ListSortDirection direction = (column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;

//set the sort order on the column
column.SortDirection = direction;

//use a ListCollectionView to do the sort.
ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(DataGrid_ParametersList.ItemsSource);

ParametersListComparer customComparer = new ParametersListComparer();
customComparer.SortDirection = direction;
customComparer.SortMemeberPath = column.SortMemberPath;

if (lcv.IsAddingNew) 
lcv.CommitNew();
if (lcv.IsEditingItem)
lcv.CommitEdit();

//apply the sort
lcv.CustomSort = customComparer;
}

2) Another way is Make a Data grid read only.

<my:DataGrid x:Name="DataGrid"                             
IsReadOnly="True"
Sorting="DataGrid_Sorting">
like image 157
ptsivakumar Avatar answered Nov 09 '22 19:11

ptsivakumar


After ListCollectiontView.AddNewItem( item ); do not forget ListCollectiontView.CommitNew(); This method ends the add transaction and saves the pending new item. Same for CommitEdit()

like image 30
Mikhail Poda Avatar answered Nov 09 '22 19:11

Mikhail Poda