Sorting of ListItems inside a Dropdownlist or Listbox is not provided by default .net framework. Either you need to sort your items at the database level (using order by) if the lists are binded with a datasource from database, or you need to write your own class which implements the IComparer interface and override the Compare method stub.

I write an example on how you write the class and override the Compare method. The compare method takes as input, 2 objects (x and y) and performs a comparison on the two objects. Passing objects as parameters will help in sorting custom object types as well as datatypes like int string etc., The function returns 0 if the two objects are equal, a number less than zero if x is less than y, and a number greater than zero if x is greater than y.

A class ListItemComparer which implements the IComparer interface and overrides the Compare method.

[code:c#]
// A class which implements the IComparer interface.
public class ListItemComparer : IComparer
{
    public int Compare(object x, object y)
    {
        ListItem li_x = (ListItem)x;
        ListItem li_y = (ListItem)y;
        CaseInsensitiveComparer c = new CaseInsensitiveComparer();
        return c.Compare(li_x.Text, li_y.Text);
    }
}
[/code]


Now, we can have a generalized static method, which takes the Dropdownlist as input and sorts it accordingly.

[code:c#]
public static void SortDropDownList(DropDownList dlList)
{
    ArrayList arl = null;
    if (dlList.Items.Count > 0)
    {
        arl = new ArrayList(dlList.Items.Count);
        foreach (ListItem li in dlList.Items)
            arl.Add(li);
     }
    arl.Sort(new ListItemComparer());
    dlList.Items.Clear();
    for (int i = 0; i < arl.Count; i++)
        dlList.Items.Add(arl[i].ToString());
}
[/code]


Now you can use this method to sort any dropdownlist by passing it to the above method.

E Screw