Hi Neelu,
you need to do a few things:
1. Add an event handler to the ListViews ColumnClick event
2. Inside this event handler you will need to set the Lists
ListViewItemSorter property to supply an object that knows how to sort the
data (see example later)
3. Call the Lists Sort() method which will cause the listview to be reordered.
The ListViewItemSorter object needs to implement IComparer so that the
control can ask it how to compare two items in the list, it will also need
to know the column index you clicked on to be able to retrieve the data from
the correct column. Depending on the column you will have to run a different
comparison algorithm (i.e. strings vs ints vs special formatting etc).
For example, pretend we have a form with a ListView called ListView1, it has
multiple columns, you need to add an even handler for the column click:
private void Form1_Load(object sender, EventArgs e)
{
this.listView1.ColumnClick += new
ColumnClickEventHandler(listView1_ColumnClick);
}
void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
this.listView1.ListViewItemSorter = new
MyListViewSorter(e.Column);
this.listView1.Sort();
}
You need to define the MyListViewSorter (or whatever you want to call it
class):
public class MyListViewSorter : IComparer
{
private int _columnIndex;
public MyListViewSorter(int columnIndex)
{
_columnIndex = columnIndex;
}
#region IComparer Members
public int Compare(object x, object y)
{
ListViewItem lvi1 = x as ListViewItem;
ListViewItem lvi2 = y as ListViewItem;
return
lvi1.SubItems[_columnIndex].Text.CompareTo(lvi2.SubItems[_columnIndex].Text);
}
#endregion
}
In your case inside the Compare method you will have to call different
functions to do the comparison depending on the index of the column the user
clicked on.
Hope that helps
Mark R Dawson
http://www.markdawson.org