Tuesday, December 3, 2013

How to sort the Listbox using C#.Net?

//calling the function
 SortListBox(lstCountry);


public static void SortListBox(ListBox lbxId)
{
 List<ListItem> lstItem = new List<ListItem>();
 Comparison<ListItem>  compare = new Comparison<ListItem> (CompareListItems);

 //Iterate through each ListItem in the Listbox, and add them to the 'List' object
 foreach (ListItem lbItem in lbxId.Items)
  {
   lstItem.Add(lbItem);
  }

 //Sort the List
 lstItem.Sort(compare);

 //Clear the Listbox passed in, and add the sorted list from above
 lbxId.Items.Clear();
 lbxId.Items.AddRange(lstItem.ToArray());
}

public static int CompareListItems(ListItem li1, ListItem li2)
{
 //Return the strings in order that have been compared:
        return String.Compare(li1.Text, li2.Text);
}

No comments:

 
Feedback Form