A WALK AROUND THE PROBLEM OF THE ABSENCE OF SORT PROPERTY IN WINDOWS MOBILE VERSION OF SYSTEM.WINDOWS.FORM.LISTVIEW
Recently, I was working on an application for Windows Mobile OS 5.0 device. I used a ListView control to display a group of names and associated numbers. I set the View property of the control to Details. But much to my chagrin, the records were not sorted. I scanned the ListView control for any property that may have to do with sorting. Of course, the ListView control has a sort property in windows form application. Interestingly, the property is absent in the windows mobile version of the .NET framework.
Thanks to resources on the internet, I was able to implement a sorting order for the listview. Here are the steps to follow to make a ListView control sort records in windows mobile application development. This trick can also be used in a windows form application.
STEP 1
I created a class that implements the IComparer interface. This class will be used to compare my objects and return the lesser or greater one
class contactsIComparer: IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
contacts contactX = (contacts)x;
contacts contactY = (contacts)y;
return contactX.getContactName.CompareTo(contactY.getContactName);
}
#endregion
}
STEP 2
Making each record to be displayed in my listView an object, I loaded all of them into an ArrayList collection. The essence of this approach is to enable comparison among the objects later using the Sort property of the ArrayList object.
ArrayList lst = new ArrayList();
For (int i=0; i < 10; i++){
lst.Add(new contacts(“Name” + i.ToString(),”Address”));
}
STEP 3
I use the Sort property of the ArrayList object to sort all its entries/records. As you can see below, I passed in, as an argument, the class that implemented the IComparer interface. The sort property uses the passed-in argument to sort the records.
lst.Sort(new contactsIComparer());
STEP 4
The last step here is to iterate through the ArrayList object (which is already sorted by now), get and add each entry to the ListView object as follows:
for (int t = 0; t < lst.Count; t++)
{
string text = lst[t].ToString();
string name = text.Substring(0, text.IndexOf(",")).Trim();
string number = text.Substring(text.IndexOf(",") + 1).Trim();
ListViewItem vItem = new ListViewItem(name);
vItem.SubItems.Add(number);
listView1.Items.Add(vItem););
}
As you can see above, I had to break up each string returned from my ArrayList object into two so that I can separate the Name from Number
No comments:
Post a Comment