ASP.NET DropDownList1.Sort – Sorting a DropDownList





Have you ever wanted to sort an ASP.NET drop down list, and tried to search for DropDownList1.Sort in the intellisense?

How dissapointing that Microsoft did not supply this.

Below I show you how to implement a SortDropDownList function that will allow you to achieve this functionality:

public void SortDropDownList(DropDownList dropDownList) //Listbox too
{
ArrayList arrayList = arrayList = new ArrayList(dropDownList.Items.Count);

foreach (ListItem listItem in dropDownList.Items)
{
arrayList.Add(listItem);
}

arrayList.Sort(new ListItemComparer());
dropDownList.Items.Clear();

for (int i = 0; i < arrayList.Count; i++)
{
dropDownList.Items.Add((ListItem)arrayList[i]);
}
}

public class ListItemComparer : IComparer
{
public int Compare(object compareObject1, object compareObject2)
{
ListItem listItem1 = (ListItem)compareObject1;
ListItem listItem2 = (ListItem)compareObject2;

CaseInsensitiveComparer caseInsensitiveComparer = new CaseInsensitiveComparer();

return caseInsensitiveComparer.Compare(listItem1.Text, listItem2.Text);
}
}

Happy developing
Robert Bertora.




Tags: , ,

Comments are closed.