Monday, August 16, 2010

How to enable a List to allow sorting on its class attributes

In my earlier post here, I had tried to convert a List to a DataView, in order to display a tabular result format in an asp:ListView control.

Once I got to display the table, I needed to sort the display based on CustomerID field of the Class “Customer”.

Thanks to Anand Malli, for having a great post on the Code Project for describing it beautifully and in a very simple, extensible manner.

Here is what I landed up doing:

Step #1: Inherited my class from IComparable

public class Customer : IComparable<Customer>
Step #2: Implement the IComparable member
public int CompareTo(Customer other)
{
throw new NotImplementedException();
}
Step #3: Add the Comparison member to the class
public static Comparison<Customer> CustomerIDComparison = delegate(Customer p1, Customer p2)
{
return p1.CustomerID.CompareTo(p2.CustomerID);
};
Step #4: Finally, getting the sort to work before setting the DataSource of the ListView.
lstCustomer.Sort(Customer.CustomerIDComparison);
And that’s it. A big thanks to Anand for sharing this information.
Technorati Tags: ,,,

No comments: