Trying to bind a sorted EditableRootList to a DataGrid

Trying to bind a sorted EditableRootList to a DataGrid

Old forum URL: forums.lhotka.net/forums/t/9458.aspx


Mike78 posted on Tuesday, August 31, 2010

I have a DataGrid on my xaml page that I would like to be sorted when the page first loads.  I realize I could just sort the data in my stored procedure, but I would prefer to do it in code.  I thought this would be easy, but it's turning out to be much more difficult than I had anticipated.

I can bind my DataGrid to my EditableRootList object (my Model) well enough, but it's the sorting that's giving me trouble.  I'm trying to do the sort in my ViewModel class with a method similar to the following.

protected override void OnRefreshed()
{
     base.OnRefreshed();
     if (Model != null)
     {
          var sortedList = (from item in Model orderby item.MyFieldName select item);               
          Model = (Business.CustomerList)sortedList;
     }
}

My code compiles, but at runtime the last line of this method raises an InvalidCastException.

Has anyone else had any luck with this situation?  I'm using Silverlight 4, C# 4, and CSLA 4.

JonnyBee replied on Tuesday, August 31, 2010

Hi,

A linq query returns just an IEnumerable not a Business.CustomerList and that is why you get an invalid cast exception

Take a look at the LinqObservableCollection class and the ToSyncList extension method that you can apply to a linq query. Something like:

var sortedList = model.ToSyncList(from item in Model orderby item.MyFieldName select item);

 

 

Mike78 replied on Tuesday, August 31, 2010

Ah, yes.  That seems to have done the trick.  My new solution is as follows.


protected override void OnRefreshed()
{
     base.OnRefreshed();

     if (Model != null)
     {
          var sortedList = Model.ToSyncList(from item in Model orderby item.MyFieldName select item);
               
          Business.CustomerList tempList = new Business.CustomerList();
          tempList.AddRange(sortedList);

          Model = tempList;               
     }                   
}


Thanks for your help.

Copyright (c) Marimer LLC