Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert an item to a listbox in its alphabetical place?

Tags:

c#

asp.net

I develop a webpage in that I display a list box items which is fetched from a database. Dynamically I added some items into it. It adds to the end of the list box, so I want to sort the list box item after I add items. I tried Arraylist for sorting, but it is not working.

like image 639
Sakthivel Avatar asked Nov 05 '09 11:11

Sakthivel


1 Answers

I was looking at a way of doing this without comparer classes, ArrayLists etc. So I thought I'd paste the method I had used for others:

Please note that my method uses LINQ to Objects, so it will only work in newer versions of the Framework.

// get a LINQ-enabled list of the list items
List<ListItem> list = new List<ListItem>(ListBoxToSort.Items.Cast<ListItem>());
// use LINQ to Objects to order the items as required
list = list.OrderBy(li => li.Text).ToList<ListItem>();
// remove the unordered items from the listbox, so we don't get duplicates
ListBoxToSort.Items.Clear();
// now add back our sorted items
ListBoxToSort.Items.AddRange(list.ToArray<ListItem>());
like image 178
Carl Heinrich Hancke Avatar answered Oct 23 '22 23:10

Carl Heinrich Hancke