Sort ListView By column

N

neelu

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.
 
G

Guest

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top