January 2018 : Instructor-led Online Course in ASP.NET Core 2.0. Conducted by Bipin Joshi. Read more...
Registration for January 2018 batch of ASP.NET Core 2.0 instructor-led online course has already started. Conducted by Bipin Joshi. Register today ! Click here for more details.

Using IComparable to perform custom sorting

Introduction

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

Create a Employee class that implements IComparable


public class Employee:IComparable
{
private string strName;
private int intAge;
private static string strSortOrder;

public Employee(string name,int age)
{
strName=name;
intAge=age;
}

public string Name
{
get
{
return strName;
}
set
{
strName=value;
}
}

public int Age
{
get
{
return intAge;
}
set
{
intAge=value;
}
}

public static string SortOrder
{
get
{
return strSortOrder;
}
set
{
strSortOrder=value;
}
}

public int CompareTo(object y)
{
string name1,name2;
int age1,age2;

switch(strSortOrder)            
{
case "ASCNAME":
	name1=this.Name;
	name2=((Employee)y).Name;
	return name1.CompareTo(name2);
case "DESCNAME":
	name1=((Employee)y).Name;
	name2=this.Name;
	return name1.CompareTo(name2);
case "ASCAGE":
	age1=this.Age;
	age2=((Employee)y).Age;
	if(age1<age2)
		return -1;
	else if(age1==age2)
		return 0;
	else
		return 1;
case "DESCAGE":
	age1=((Employee)y).Age;
	age2=this.Age;
	if(age1<age2)
		return -1;
	else if(age1==age2)
		return 0;
	else
		return 1;
default:
	name1=this.Name;
	name2=((Employee)y).Name;
	return name1.CompareTo(name2);

}
}
}

Here, we will set the SortOrder property (note that it is a static property) to indicate how the sorting should happen. Use use it internally in CompareTo method to decide the object property to sort on. Since this property is independent of any instance of the class we made it shared.

WebForm with DataGrid

Now, you need to create a web form with a DataGrid on it. Set AllowSorting prperty of teh DataGrid to true and add two bound coulmns. The Name boundcolumn should have sort expression set to "ASCNAME" and Age boundcolumn should have set it to "ASCAGE". Note that this is the SortOrder that we used internal to teh Employee class. Next, you need to create a function called BindGrid that will create instances of Employee class and bind the grid.
private void BindGrid(string sortfield)
{
ArrayList=new ArrayList();
Employee emp1 = new Employee("John", 30);
Employee emp2 = new Employee("Henry", 50);
Employee emp3 = new Employee("Bill", 20);
arr.Add(emp1);
arr.Add(emp2);
arr.Add(emp3);
if(sortfield != "")
{
    Employee.SortOrder = sortfield;
    arr.Sort();
}
DataGrid1.DataSource = arr;
DataGrid1.DataBind();
}
You will call this function in the Page_Load of the form and in the SortCommand event handler of teh DataGrid.
private void Page_Load(object sender,
EventArgs e)
{
    if(!Page.IsPostBack)
    {
       BindGrid("");
    }
}
private void DataGrid1_SortCommand
(object sender, 
DataGridSortCommandEventArgs e) 
{
        BindGrid(e.SortExpression);

}

Bipin Joshi is a software consultant, an author and a yoga mentor having 22+ years of experience in software development. He also conducts online courses in ASP.NET MVC / Core and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 19 December 2003


Tags : .NET Framework VB.NET C# Components