There exist much, much simpler approach.
First, instead of a custom CommandName
, you put a built-in name into the sort link button. The name is Sort
.
You have then
<asp:LinkButton ID="SortByName" runat="server" CommandArgument="Name" CommandName="Sort" />
Then, on your ObjectDataSource
you add the SortParameterName
to be something like OrderBy
:
<ObjectDataSource .... SortParameterName="OrderBy" />
Then you modify your data provider method to be:
public IEnumerable<ListDocumentsResult> SelectItems(
string OrderBy,
int maximumRows,
int startRowIndex)
The data source will provide the value automatically based on the command argument (Name
) and it will automatically append DESC
whenever you click the command button for the second time (it is because the ListView
persists the state of sort order in its viewstate automatically, you don't have to reinvent this!)
Then, you don't need this ugly delegates to order by strings for linq. Instead, download the Dynamic Linq library:
find the Dynamic.cs
file, include it in your project and it will add a bunch of additional linq operators, including the OrderBy
which accepts strings and which automatically supports DESC
(!).
You then just
public IEnumerable<ListDocumentsResult> SelectItems(
string OrderBy,
int maximumRows,
int startRowIndex)
{
Controller.ListDocuments(new ListDocumentsRequest())
.OrderBy(OrderBy)
.Skip(startRowIndex)
.Take(maximumRows);
}
This is just as simple!
Be warned though that there's a small bug (or an inconvenience) in the dynamic linq - it throws an exception when the sort order is empty.
Find then this code (line 47 and down)
public static IQueryable OrderBy(this IQueryable source, string ordering, params object[] values) {
if (source == null) throw new ArgumentNullException("source");
if (ordering == null) throw new ArgumentNullException("ordering");
and change it manually to
public static IQueryable OrderBy(this IQueryable source, string ordering, params object[] values) {
if ( string.IsNullOrEmpty( ordering ) ) return source;
if (source == null) throw new ArgumentNullException("source");
if (ordering == null) throw new ArgumentNullException("ordering");
Done.