Many web applications use DataSet to bind data with controls such as DataGrid. DataSet allows you to easily sort the data using objects such as DataView. However, in pure OO design instead of sending DataSet to the presentation layer you may want to send an object array. In this case how will you allow users to sort the data? That is what this article explains. Keep reading.
IComparable interface
Sorting is nothing but ordering the list of items in a perticular way. In order to sort any list the underlying system must be able to compare various elements of the list so that they can be rearranged based on the result of comparison. The System namespace contains an interface called IComparable that can be used to provide such custom comparison mechanism for your classes. The IComparable interface consists of a single method called CompareTo that accepts the object to compare with current instance. The method should return 0 if both the instances are equal, less than 0 if current instance is less than supplied instance and greater than 0 if current instance is greater than the supplied one.
[C#]
int CompareTo(object obj);
[Visual Basic]
Function CompareTo(ByVal obj As Object) As Integer
How does this solves our problem?
DataGrid web control can be bound with variety of data sources such as DataSet, DataTable and ArrayList. If we want to bind the grid with an a list of objects ArrayList can be good choice for this binding. ArrayList class has a method called Sort() that checks whether each element has implemented IComparable interface. If it does implements then the CompareTo() method implemented in the class will be used to sort the various elements. That means in order to implement custom sorting we need to:
- Create a class (say Employee) that implements IComparable
- Create an ArrayList
- Add instances of Employee class to the ArrayList
- Bind the ArrayList to the DataGrid
- Handle the SortCommand event of the DataGrid
[Read More]