Sorting a DropDownList using ArrayList

By Riley K

In most of the cases we want to dispaly a DDL in a sorted order, lets see how to do this using ArrayList

Consider the below DDL:

<asp:DropDownList ID="ddlSort" runat="server"  AutoPostBack="true">
    <asp:ListItem Text="India" Value="1" ></asp:ListItem>
    <asp:ListItem Text="USA" Value="2" ></asp:ListItem>
    <asp:ListItem Text="Canada" Value="3" ></asp:ListItem>
    <asp:ListItem Text="Egypt" Value="4" ></asp:ListItem>
    <asp:ListItem Text="Japan" Value="5" ></asp:ListItem>
    <asp:ListItem Text="China" Value="6" ></asp:ListItem>
    <asp:ListItem Text="Dubai" Value="7" ></asp:ListItem>
    <br />
    <br />
    <asp:Button ID="btnSort" Text="Sort DDL" runat="server" onclick="btnSort_Click" />

on click of a button i am sorting the ddl

public void SortDDL(DropDownList ddlControl)

        ArrayList textList = new ArrayList();
        ArrayList valueList = new ArrayList();
//I am adding the DDL items to array list and sorting using the ArrayList Sort method
        foreach (ListItem li in ddlControl.Items)
//using the FindByText method i am finding the corresponding value of eact item in DDl and adding to valueList ArrayList
        foreach (object item in textList)
            string value = ddlControl.Items.FindByText(item.ToString()).Value;

//now i am repopulating the DDL with the new sorted values
        for (int i = 0; i < textList.Count; i++)
            ListItem objListItem = new ListItem(textList[i].ToString(), valueList[i].ToString());

    protected void btnSort_Click(object sender, EventArgs e)


What i have done is i took 2 arraylist one for ddl text and other for its value and sorting the array list and again populating the DDL, very simple and efficient.

Sorting a DropDownList using ArrayList  (1172 Views)