The Data Source '...’ Does Not Support Sorting With IEnumerable Data
We are currently refactoring a web application, which uses ObjectDataSources extensively. There are places in our app,
where they are used for sorting grids, but there is a problem. We switched from DataTables to collections and now an
exception occurs:
12
The data source ‘ods_DataSource’ does not support sorting with IEnumerable data.
Automatic sorting is only supported with DataView, DataTable, and DataSet.
As Pradeem wrote on his blog there are two solutions to the above issue:
Implement custom sorting
Change IEnumerable datatype into one of these datatypes.
Eventually we would implement the former, but for the time being Pradeem gives a solution. There is however something
wrong with his code so below I give you his snippet slightly modified to be an Extension method.
publicstaticclassUtil{publicstaticDataTableToDataTable<T>(thisIEnumerable<T>varlist){DataTabledtReturn=newDataTable();// column namesPropertyInfo[]oProps=null;// Could add a check to verify that there is an element 0foreach(Trecinvarlist){// Use reflection to get property names, to create table,// Only first time, others will followif(oProps==null){oProps=((Type)rec.GetType()).GetProperties();foreach(PropertyInfopiinoProps){// Note that we must check a nullable type// else method will throw and errorTypecolType=pi.PropertyType;if((colType.IsGenericType)&&(colType.GetGenericTypeDefinition()==typeof(Nullable))){// Since all the elements have same type// you can just take the first element and get typecolType=colType.GetGenericArguments()[0];}dtReturn.Columns.Add(newDataColumn(pi.Name,colType));}}DataRowdr=dtReturn.NewRow();// Iterate through each property in PropertyInfoforeach(PropertyInfopiinoProps){// Handle null values accordinglydr[pi.Name]=pi.GetValue(rec,null)==null?DBNull.Value:pi.GetValue(rec,null);}dtReturn.Rows.Add(dr);}return(dtReturn);}}