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
ListViewItemSor ter 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 ListViewItemSor ter 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(obje ct sender, EventArgs e)
{
this.listView1. ColumnClick += new
ColumnClickEven tHandler(listVi ew1_ColumnClick );
}
void listView1_Colum nClick(object sender, ColumnClickEven tArgs e)
{
this.listView1. ListViewItemSor ter = new
MyListViewSorte r(e.Column);
this.listView1. Sort();
}
You need to define the MyListViewSorte r (or whatever you want to call it
class):
public class MyListViewSorte r : IComparer
{
private int _columnIndex;
public MyListViewSorte r(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
"neelu" wrote:
I have four columns in listview.
SR Number Part# DES Qty Weight
59 9410106800 Nut 10 0.03
60 90304ge800 Helmet 5 0.325
61 9635439604 Cap 15 0.421
62 25340h1245 Shoes 2 0.001
I want that when I click on column part# it sort the list View
according to part# column. If I click on ColumnName DES it sort the
whole listView according to DES Column as so on. All rows must be
sorted according to the column I clicked. How can I do that.
Thanks.