Sorting a dropdown list

  • Thread starter Thread starter Morten
  • Start date Start date
M

Morten

Hi!

I've created a webform with a dropdown to which I've added some static
items. I'm adding some extra items in my code. I'd like to sort the items
after I've finished adding my new items. Can someone provide an example of
how to do this?

Thanks in advance for your help.

Morten
 
First of all, keep in mind that sorting the items will change each item's index. Make sure this won't cause any problems in your code.

The most straight-forward approach is to copy the items to an array, sort them, clear the original item list, and copy the sorted items back into the drop down list's items collection.

object[] SortedItems = new object[ddlMyList.Items.Count];
for (int i = 0; i < SortedItems.Length; i++)
{
SortedItems = cbTest.Items;
}
Array.Sort(SortedItems);
ddlMyList.Items.Clear();
ddlMyList.Items.AddRange(SortedItems);
 

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

Back
Top