views:

1531

answers:

1

Hi,

I have a WPF Datagrid that I am using with a number of columns. One of the columns has some elements that are sometimes null and this causes an exception when I try and sort on this column.

The definitions of the columns is something like:

<dg:DataGrid.Columns>
  <dg:DataGridTextColumn Binding="{Binding MyObject.Field1}" Header="Field1" Width="Auto" />
  <dg:DataGridTextColumn Binding="{Binding MyObject.Field2.SubField}" Header="Field2" Width="Auto" />
</dg:DataGrid.Columns>

If I sort on Field1 column it is fine, if I sort on Field2 column and there are no null Field2 objects it is fine, but sometimes there are and the DataGrid tries to sort on the SubField (I guess) and hits a null exception:

System.InvalidOperationException was unhandled
  Message=The SortDescriptions added are not valid. The probable solutions are to set the CanUserSort on the Column to false, or to use SortMemberPath property on the Column, or to handle the Sorting event on DataGrid.

I have tried setting SortMemberPath to "MyObject.Field2.SubField" but of course this doesn't fix it since Field2 is still sometimes null. I wondered about trying to use a converter where I set the SortMemberPath and have that converter return string.empty for any null elements but couldn't get it to work.

I also tried adding "TargetNullValue={x:Static sys:String.Empty}" within the binding of these columns but it still did not work.

Any advice/suggestions would be most appreciated. Thanks, Will

+4  A: 

Hi Will.

General advice would be: Don't use SortMemberPath. Not only because of the problem you've just met. But also because they are ultraslow.

Instead use CustomSort property of the ListCollectionView class. For more details read "Improving Microsoft DataGrid CTP sorting performance" and "Improving Microsoft DataGrid CTP sorting performance - Part 2". Although it says "imporve performance" it also shows how to fix your problem.

Hope this helps :).

Anvaka
Thanks Anvaka,Great links, I have implemented the custom sort as above and even for the relatively modest data load in my grid the sort speed is noticeably quicker. The only downside is that I have lost the ability to do multiple sorts now since any new custom sort overwrites the previous. I am trying to find a way to do this now, could be a new question!
WillH